gpt4 book ai didi

c - 字符串突然变空,即使它在片刻之前是完整的

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

我正在尝试为命令行输入编写一个简单的 C 函数来检查用户的输入是否太长。我留下了调试打印以显示发生了什么。

bool read_line(char str[])
{
char c = '\0';
int max_chars = sizeof(str) / sizeof(char);
printf("%d\n", max_chars);
int i = 0;
while (true) {
c = getchar();
if (c == '\n' || c == EOF) {
break;
}
printf("The value of c is %c\n", c);
i++;
printf("The value of i is %d\n", i);
if (i > max_chars) {
return false;
}
printf("Inserting character %c\n", c);
str[i] = c;
printf("str[i] is %c\n", str[i]);
}

return true;
}

测试代码为:

char str[] = {[0 ... SIZE - 1] = 0};
bool length_valid = read_line(str);
if (!length_valid) {
printf("Input too long\n");
return 1;
}
puts(str);
return 0;

这是运行程序的输出;我输入了“forth”这一行。

8
forth
The value of c is f
The value of i is 1
Inserting character f
str[i] is f
The value of c is o
The value of i is 2
Inserting character o
str[i] is o
The value of c is r
The value of i is 3
Inserting character r
str[i] is r
The value of c is t
The value of i is 4
Inserting character t
str[i] is t
The value of c is h
The value of i is 5
Inserting character h
str[i] is h
8
forth
The value of c is f
The value of i is 1
Inserting character f
str[i] is f
The value of c is o
The value of i is 2
Inserting character o
str[i] is o
The value of c is r
The value of i is 3
Inserting character r
str[i] is r
The value of c is t
The value of i is 4
Inserting character t
str[i] is t
The value of c is h
The value of i is 5
Inserting character h
str[i] is h
<Empty line>

该字符串在片刻之前清楚地显示为充满了字符,但不知何故在其间它变成了空值。

最佳答案

EOF 有点正确,但更简单的解决方法是使 max_chars 成为如下参数:

bool read_line(char str[], int max_chars)

...然后调用它:

bool length_valid = read_line(str, sizeof(str));

...这应该可以帮助您完成大部分工作。

关于c - 字符串突然变空,即使它在片刻之前是完整的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22339374/

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