Using scanf to read in certain amount of characters in C?

倾然丶 夕夏残阳落幕 提交于 2020-06-08 04:30:09

问题


I am having trouble accepting input from a text file. My program is supposed to read in a string specified by the user and the length of that string is determined at runtime. It works fine when the user is running the program (manually inputting the values) but when I run my teacher's text file, it runs into an infinite loop.

For this example, it fails when I am taking in 4 characters and his input in his file is "ABCDy". "ABCD" is what I am supposed to be reading in and 'y' is supposed to be used later to know that I should restart the game. Instead when I used scanf to read in "ABCD", it also reads in the 'y'. Is there a way to get around this using scanf, assuming I won't know how long the string should be until runtime?


回答1:


Normally, you'd use something like "%4c" or "%4s" to read a maximum of 4 characters (the difference is that "%4c" reads the next 4 characters, regardless, while "%4s" skips leading whitespace and stops at a whitespace if there is one).

To specify the length at run-time, however, you have to get a bit trickier since you can't use a string literal with "4" embedded in it. One alternative is to use sprintf to create the string you'll pass to scanf:

char buffer[128];

sprintf(buffer, "%%%dc", max_length);
scanf(buffer, your_string);

I should probably add: with printf you can specify the width or precision of a field dynamically by putting an asterisk (*) in the format string, and passing a variable in the appropriate position to specify the width/precision:

int width = 10;
int precision = 7;
double value = 12.345678910;

printf("%*.*f", width, precision, value);

Given that printf and scanf format strings are quite similar, one might think the same would work with scanf. Unfortunately, this is not the case--with scanf an asterisk in the conversion specification indicates a value that should be scanned, but not converted. That is to say, something that must be present in the input, but its value won't be placed in any variable.




回答2:


Try

scanf("%4s", str)



回答3:


You can also use fread, where you can set a read limit:

char string[5]={0};
if( fread(string,(sizeof string)-1,1,stdin) )
  printf("\nfull readed: %s",string);
else
  puts("error");



回答4:


You might consider simply looping over calls to getc().



来源:https://stackoverflow.com/questions/4404368/using-scanf-to-read-in-certain-amount-of-characters-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!