Reputation: 123
In the below program, I want to encrypt a sentence. However it is giving incomplete output when space comes. Any help will be highly useful.
#include<stdio.h>
#include<string.h>
main()
{
printf("Enter a string : ");
char c[100];
scanf("%s",c);
int i;
for(i=0;i<100;i++)
{
if((c[i]>='A'&&c[i]<='Z')||(c[i]>'a'&&c[i]<'z'))
{
c[i]+=13;
if(!(c[i]>='A'&&c[i]<='Z')||(c[i]>'a'&&c[i]<'z'))
c[i]-=26;
}
}
printf("Encrypted string is : %s\n",c);
}
Thanks in advance
Upvotes: 2
Views: 107
Reputation: 3870
If you want to scan spaces means don't use %s
format specifier. Use %[^\n]
format specifier, It will scan everything except New line (\n
).
scanf("%[^\n]",c); // Fix 1
If you use scanf
for scanning the user input, no need to append NULL
at the end. It will be automatically added.
In loop no need to check for whole array(up to 100 characters) for(i=0;i<100;i++)
like this, If your input is 4 or 5 character means unnecessarily it will check for remaining location so it will give you some garbage values. So limit the loop to check the user input-
for(i=0;c[i];i++) or for(i=0;c[i] != '\0';i++) //Fix 2
Both are same here. When the null character is found it will terminate the loop.
Try this code-
#include<stdio.h>
#include<string.h>
int main()
{
int i;
char c[100];
printf("Enter a string : ");
scanf("%[^\n]",c);
for(i=0;c[i];i++)
{
if((c[i]>='A'&&c[i]<='Z')||(c[i]>'a'&&c[i]<'z'))
{
c[i]+=13;
if(!(c[i]>='A'&&c[i]<='Z')||(c[i]>'a'&&c[i]<'z'))
c[i]-=26;
}
}
printf("Encrypted string is : %s\n",c);
return 0;
}
Upvotes: 0
Reputation: 41017
scanf
stops reading at whitespace, change to fgets
:
fgets(c, sizeof c, stdin);
You can skip the trailing newline using:
char c[100], *p;
fgets(c, sizeof c, stdin);
if ((p = strchr(c, '\n')) != NULL) {
*p = '\0'; /* remove newline */
}
Also, consider using
if (isalpha((unsigned char)c[i]))
instead of
if((c[i]>='A'&&c[i]<='Z')||(c[i]>'a'&&c[i]<'z'))
Don't forget to include <ctype.h>
Upvotes: 5