使用 scanf 在 C 中读取一定数量的字符? [英] Using scanf to read in certain amount of characters in C?

查看:53
本文介绍了使用 scanf 在 C 中读取一定数量的字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法接受来自文本文件的输入.我的程序应该读入用户指定的字符串,并且该字符串的长度在运行时确定.当用户运行程序(手动输入值)时它工作正常,但当我运行我老师的文本文件时,它会进入无限循环.

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.

对于这个例子,当我输入 4 个字符并且他在他的文件中输入的是ABCDy"时,它失败了.ABCD"是我应该阅读的内容,而y"应该在稍后用于知道我应该重新启动游戏.相反,当我使用 scanf 读取ABCD"时,它也会读取y".有没有办法使用 scanf 来解决这个问题,假设我不知道字符串应该在运行时多长时间?

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?

推荐答案

通常,您会使用诸如 "%4c""%4s" 之类的东西来阅读最多 4 个字符(区别在于 "%4c" 读取接下来的 4 个字符,而 "%4s" 跳过前导空格并在空格处停止,如果有一个).

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).

然而,要在运行时指定长度,您必须变得有点棘手,因为您不能使用嵌入了4"的字符串文字.一种替代方法是使用 sprintf 创建您将传递给 scanf 的字符串:

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);

我应该补充一点:使用 printf,您可以通过在格式字符串中放置星号 (*) 并传递一个字段来动态指定字段的宽度或精度适当位置的变量以指定宽度/精度:

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);

鉴于 printfscanf 格式字符串非常相似,人们可能认为 scanf 也是如此.不幸的是,情况并非如此——scanf 转换规范中的星号表示应该扫描但不转换的值.也就是说,输入中必须存在的东西,但它的值不会放在任何变量中.

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.

这篇关于使用 scanf 在 C 中读取一定数量的字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆