Scanset issue in C language

Status
Not open for further replies.

shaswat

Advanced Member level 4
Joined
Jul 2, 2013
Messages
115
Helped
1
Reputation
2
Reaction score
1
Trophy points
18
Visit site
Activity points
963
Hello Everyone!!

While I was trying some online C language quiz, I was stuck in problem where the constraints was to take strings that only have 'R' an 'S' letter. I searched it online and got some suitable resource about the scanset https://www.geeksforgeeks.org/scansets-in-c/. However, I have not got complete answer as I need to take input inside the while statement.

Here is the snippet:

Code:
#if 1

int main()
{
    int loop=10;
    u8 str[122];
    while(loop--)
    {
        scanf("%[^\n]s", str);
        printf("%s\n",str);
    }
    return 0;
}
#endif // 1

This code just take input only as first time, and print the same on the output window for 10 times.
I am not sure how to take string after each display of printf function.

Any help or hint would be really appreciable.
 

HI.
There are a number of issues at work in your little proggy. But first, a couple of things to know:
1. scanf will not skip leading whitespace when used with scanners;
2. scanf will probably leave the output string unchanged if it fails (failure should be determined from the returned int);
3. Subsequent scanf reads will read and match from where the last scanf stopped matching.
Knowing the above, this is what I think happened:
- first time in the loop, scanf reads whatever you give it until new line;
- subsequent scanf read and attempt to match from new line and fail (the string is preserved, however);
- so on until the end.
In an an attempt to fix this, you'll want to get rid of all chars not matched (new line, in your case) by, say, adding to the format specifier. I say attempt, because this can still fail in so many other ways...
Arthur
 

Once I tried to use 'scanf' with ARM for parse values from string. It took something about 10k words of memory! Crazy. I decided to wrote by own parser and never use this function anymore
 

Status
Not open for further replies.

Similar threads

Cookies are required to use this site. You must accept them to continue using the site. Learn more…