gpt4 book ai didi

c - 如何在c程序中而不是从文件中扫描行

转载 作者:太空宇宙 更新时间:2023-11-04 03:21:49 24 4
gpt4 key购买 nike

如何用c程序扫描用户输入的总行?

我尝试了 scanf("%99[^\n]",st),但是当我在这个扫描语句之前扫描一些东西时它不起作用。如果这是第一个扫描语句它就起作用了.

最佳答案

How to scan total line from user input with c program?

读取一行输入的方法有很多,您对单词扫描的使用表明您已经专注于scanf() 作业的函数。这很不幸,因为尽管您可以(在某种程度上)使用 scanf() 实现您想要的,但它绝对不是阅读一行的最佳工具。

如评论中所述,您的 scanf() 格式字符串将停止在换行处,因此下一个 scanf() 将首先找到那个换行符,它不能匹配[^\n](这意味着任何除了换行符)。由于换行符只是另一个空白字符,在转换前添加一个空格会悄无声息地吃掉它 ;)

但现在有了更好的解决方案:假设您只想使用标准 C 函数,那么已经有一个函数可以完全读取一行:fgets() .下面的代码片段应该解释它的用法:

char line[1024];
char *str = fgets(line, 1024, stdin); // read from the standard input

if (!str)
{
// couldn't read input for some reason, handle error here
exit(1); // <- for example
}

// fgets includes the newline character that ends the line, but if the line
// is longer than 1022 characters, it will stop early here (it will never
// write more bytes than the second parameter you pass). Often you don't
// want that newline character, and the following line overwrites it with
// 0 (which is "end of string") **only** if it was there:
line[strcspn(line, "\n")] = 0;

请注意,您可能要使用 strchr() 检查换行符相反,所以你实际上知道你是否拥有整条线或者你的输入缓冲区可能太小了。在后一种情况下,您可能需要再次调用 fgets()

关于c - 如何在c程序中而不是从文件中扫描行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45055398/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com