gpt4 book ai didi

c - 修复了带有空格键和 EOF 检查的字符串

转载 作者:行者123 更新时间:2023-11-30 17:36:29 28 4
gpt4 key购买 nike

好的,我有这段代码:

struct Computer
{
char name[20];
float hdd;
int price;
int ram;
};

struct Computer list[7];
int n = 0;

for(n; n < 7; n++)
{

printf("\nEnter PC name, 20 characters:");
/* here should be name entry for list[n].name */
}

很多方法都行不通。我尝试了 fgets()getch()scanf() 和很多其他方法,但它要么不起作用,要么没有有足够的功能。

fgets(list[n].name, 20, stdin) 无法识别条目中的 EOF,这是必需的。

list[n].name[counterChar] = getch() 有一些奇怪的行为,并且有许多带有回显的例程。

scanf("%c", &list[n].name[counterChar]) 让用户在每个符号后按 Enter 键。

我需要的是:名称限制为20个字符,包括空格,如果EOF,则跳出循环。

最佳答案

这样的事情会起作用:

int ret; 
...
{
ret = scanf(" %19[^\n]", list[n].name);
if(ret == EOF)
break;

为了澄清这段代码的作用:

  • 这将读取 19 个字符(为空终止符留出 1 个空格)。如果您将完整的 20 读入 name[20],您将填满数组,而不会为 scanf() 留出空间。附加空终止符 ('\0')。如果您确实想要 20 个字符,那么您需要将数组增加到 name[21]

  • 格式字符串利用 negated scanset并告诉 scanf() 在换行符处停止,而不是“全空白”字符。这意味着它将读取空格,但也会读取其他空白字符(例如制表符、换行符等)。

    如果不是这样,您可以通过在其中添加更多“停止”字符来调整扫描集。例如,如果您希望它停在换行符或制表符上,您可以执行以下操作:"%19[^\n\t]"

  • 格式字符串在初始的 "% 之间还有一个空格,这是故意的。它告诉 scanf() 忽略 stdin 缓冲区上留下的任何空格。在循环中使用 scanf() 将保留前一个换行符 ('\n' )在缓冲区上。

  • 最后,检查 scanf() 的返回值,以打破您得到 EOF 的循环。您可以看到,如果遇到 EOF 而不是 man page 中的字符串,您将得到以下结果: :

The value EOF is returned if the end of input is reached before either the first successful conversion or a matching failure occurs.

关于c - 修复了带有空格键和 EOF 检查的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22668719/

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