Bongfeldt
Bongfeldt

Reputation: 3

C How do I get scanf to stop on blank/space?

I need my scanf to stop when it findes a spac/blank.

For exsample

If I type in "E E", I only need 1 "E", so it has to stop at space/blank.

char end[] = "E";
char end1[] = "End";
char info[] = "";

while(run) {
 scanf("%s", &info);
 ...
 else if(strcmp(info, end) == 0 || strcmp(info, end1) == 0) {
    end_of_turn();
 }
 ...
}

Now the problem here is that If I type in "E E", it will run "end_of_turn" twice.

Does anyone know why it is so?

Edit:

Okay I can't break the while loop, because that would stop the program.

Upvotes: 0

Views: 3870

Answers (3)

Gavin Smith
Gavin Smith

Reputation: 3154

It looks like it is possible to use the %[ format specifier to only match certain characters. To exclude spaces, I think you would use %[^ ].

Upvotes: 0

Frederico Schardong
Frederico Schardong

Reputation: 2095

Loop through the string stored in info searching for the space character ' ', if you find it then set the rest of the string to \0

Upvotes: -1

Aniket Inge
Aniket Inge

Reputation: 25705

use break to break out of the while loop? after calling end_of_turn()

Or use a goto statement if you do not want to break out of the loop.

You can also get all the characters from the input stream and then discard them using the code: while(getchar() != '\n') ;

Upvotes: 2

Related Questions