Reputation: 23
#include<stdio.h>
void main()
{
char str1[100];
char str2[100];
printf("\n Enter the first String\n");
scanf("%[^\n]s",str1);
printf("Enter the second String");
scanf("%[^\n]s",str2);
printf("\n The strings are %s %d \n",str1,i);
}
Upvotes: 0
Views: 164
Reputation: 30926
Well the thing is you press Enter and the '\n'
stays in stdin
which is consumed as string in second scanf()
.
You can put a dummy getchar()
between two scanf()
. That will solve the problem because it will consume the '\n'
that is not consumed by the previous scanf
.
The way you said that you are reading a word
- you are basically reading lines seperated by '\n'
.
A better way would be to use fgets()
. It serves two way it will solve the \n
consumption problem and the other thing is fgets()
will read a line and provides much better control than scanf()
.
No. It is not the case, it is reading the \n
from the previous line you entered.
Also few things you should know about fgets
. It will consume the \n
also. So your string will contain the \n
as character. In case you don't want that then you can do this
str[strcspn(str,"\n")]='\0'
char *fgets(char * restrict s, int n, FILE * restrict stream);
The
fgets
function reads at most one less than the number of characters specified byn
from the stream pointed to bystream
into the array pointed to bys
. No additional characters are read after a new-line character (which is retained) or after end-of-file. A null character is written immediately after the last character read into the array.
Also check the return value of fgets()
to know if it is successful or not.
If the (EOF)End-of-File is encountered and no characters have been read, fgets
returns NULL
.
So the code will be
if( fgets(str1, 100, stdin) ){
// successfully read the string.
str1[strcspn(str1,"\n")]='\0'; ///removing `'\n'`
}
So here you can get in input the string but along with that \n
. We are overwriting it if the call is successful.
#include<stdio.h>
#include<string.h>
#define MAXLEN 100
int main()
{
char str1[MAXLEN];
char str2[MAXLEN];
printf("\n Enter the first line\n");
if( fgets(str1,MAXLEN,stdin) ){
str1[strcspn(str1,"\n")]='\0';
}
else {
fprintf(stderr,"Line not read");
exit(EXIT_FAILURE);
}
printf("\n Enter the second line\n");
if( fgets(str2,MAXLEN,stdin) ){
str2[strcspn(str2,"\n")]='\0';
}
else {
fprintf(stderr,"Line not read");
exit(EXIT_FAILURE);
}
printf("\n The strings are \n(%s) \n%s \n",str1,str2);
return EXIT_SUCCESS;
}
Upvotes: 0
Reputation: 28830
Since you want to read a whole line, use fgets
. At least you have some control over the string length input, and no need to deal with scanf
peculiarities
printf("\n Enter the first String\n");
fgets(str1, 100, stdin);
printf("Enter the second String");
fgets(str2, 100, stdin);
printf("\n The strings are %s %s \n",str1,str2);
Note that the trailing \n
is still in the strings (if they were 98 chars length max).
Worth reading - scanf vs fgets
Upvotes: 1