开发者

scanf problem in input

开发者 https://www.devze.com 2023-03-28 03:19 出处:网络
hi I am having problems using scanf when reading two strings with spaces consecutively char name[50] = {0};

hi I am having problems using scanf when reading two strings with spaces consecutively

char name[50] = {0};
char address[100] = {0};
char name1[50] = {0};
char address1[100] = {0};
int size = 0;
//input = fopen("/dev/tty","r+");
//output = fopen("/dev/tty","w");
printf("\nenter the name:");
scanf("%[^\n]s",name);
//fgets(name,sizeof(name),input); // this works fine
printf("\ne开发者_运维问答nter the address:");
scanf("%[^\n]s",address);
//fgets(address,sizeof(address),input); // this works fine

the input for address is not taken at all.. maybe it takes the return key as an input?


The newline ('\n') character is still on the input stream after the first scanf call, so the second scanf call sees it immediately, and immediately stops reading.

I notice that you mention fgets in comments - why not use that ? It does what you want to do quite well.


You have a couple of problems.

As @sander pointed out, you're not doing anything to clear the newline out of the input buffer.

You've also used %[^\n]s -- but the s isn't needed for (nor it is part of) a scanset conversion. Since it's not part of the conversion, scanf attempts to match that character in the input -- but since you've just read up to a new-line (and not read the newline itself) it's more or less demanding that 's' == '\n' -- which obviously can't be, so the scan fails.

To make this work, you could use something like this:

scanf("%49[^\n]%*c", name);
scanf("%99[^\n]%*c", address);

As to why you'd want to use this instead of fgets, one obvious reason is that it does not include the trailing (and rarely desired) newline character when things work correctly. fgets retaining the newline does give you one result that can be useful though: the newline is present if and only if the entire content of the line has been read. If you're really concerned about that (e.g., you want to resize your buffer and continue reading if the name exceeds the specified size) you can get the same with scanf as well -- instead of using %*c for the second conversion, use %c, and pass the address of a char. You read the entire line if and only if you've read a newline into that char afterwards.

0

精彩评论

暂无评论...
验证码 换一张
取 消