I was asked to do a work in C when I\'m supposed to read from input until there\'s a space and then until the user presses enter. If I do this:
scanf(\"%2000
scanf("%2000s %2000[^\n]", a, b);
#include <stdio.h>
int main()
{
char a[5],b[10];
scanf("%2000s %2000[^\n]s",a,b);
printf("a=%s b=%s",a,b);
}
Just write s in place of \n :)
scanf
(and cousins) have one slightly strange characteristic: any white space in the format string (outside of a scanset) matches an arbitrary amount of white space in the input. As it happens, at least in the default "C" locale, a new-line is classified as white space.
This means the trailing '\n'
is trying to match not only a new-line, but any succeeding white-space as well. It won't be considered matched until you signal the end of the input, or else enter some non-white space character.
To deal with this, you typically want to do something like this:
scanf("%2000s %2000[^\n]%c", a, b, c);
if (c=='\n')
// we read the whole line
else
// the rest of the line was more than 2000 characters long. `c` contains a
// character from the input, and there's potentially more after that as well.
use getchar and a while that look like this
while(x = getchar())
{
if(x == '\n'||x == '\0')
do what you need when space or return is detected
else
mystring.append(x)
}
Sorry if I wrote a pseudo-code but I don't work with C language from a while.
Sounds like a homework problem. scanf() is the wrong function to use for the problem. I'd recommend getchar() or getch().
Note: I'm purposefully not solving the problem since this seems like homework, instead just pointing you in the right direction.
//increase char array size if u want take more no. of characters.
#include <stdio.h>
int main()
{
char s[10],s1[10];
scanf("\n");//imp for below statement to work
scanf("%[^\n]%c",s);//to take input till the you click enter
scanf("%s",s1);//to take input till a space
printf("%s",s);
printf("%s",s1);
return 0;
}