简体   繁体   中英

scanf doesn't assign value to a second variable

I've been trying to read some input from the user in C, but it doesn't seem to work as I wish it would have. I try to read a string until the user writes a colon, and then assign the colon (':') into a different variable. It works perfectly unless the colon is the first character. In that case, it simply assigns a value of -52 to both variables and reads the colon in the next scanf. I try to make it so the colon will be assigned to the second variable, even when it's first. I've tried looking online but couldn't find any solution... Any tip will be very appriciated, thanks!

My attempt:

char ch, name[200];
scanf("%[^:]%c", &name, &ch);
printf("%s\n%c\n", name, ch);

for a valid input such as:

Nadav Freedman: rest_of_input

it works and assigns "Nadav Freedman" to name and ':' to ch

but for an invalid input such as:

: rest_of_input

it simply doesn't assign any value to the variables, although I would like to save the colon to ch .

scanf stops reading as soon as any of the specifier provided doesn't match the input, so in your case if the %[^:] fails the function stops reading and the %c specifier isn't processed.

So to force it to read the colon use 2 scanf s instead of 1:

char ch, name[200];
if(scanf(" %199[^:]", name) != 1) name[0] = '\0';
scanf("%c", &ch);
printf("%s\n%c\n", name, ch);

OBS: I've also added the leading space to eliminate leading blank characters. And limited it to read up to 199 characters, so as not to exceed the size of the array name . And also changed it to update the array name to store an empty string if the first scanf fails to read anything.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM