字符串突然变空,即使它已经很久了

时间:2014-03-12 00:09:59

标签: c validation cstring

我试图为命令行输入编写一个简单的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;

这是运行程序的输出;我进入了第34行"。

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>

字符串清晰地显示出前一刻充满了人物,但在某段时间内它已变为空。

2 个答案:

答案 0 :(得分:1)

EOF类似于它是正确的,但更容易解决的方法是使max_chars成为如下参数:

bool read_line(char str[], int max_chars)

...然后通过以下方式调用它:

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

......这应该可以帮到你那里。

答案 1 :(得分:0)

  

int max_chars = sizeof(str)/ sizeof(char);

应该是

int max_chars = strlen(str);

因为:
sizeof(char) 已定义 1
sizeof(char*)取决于您的计算机,而不是字符串的长度。

无论哪种方式,本程序都不会给您任何有用的信息:
一旦你纠正错误,你基本上将测试strlen(str) <= strlen(str),这显然应该是真的。
在将合适的strlen(len) <= BUFFSIZE定义为宏之后,您可能会发现在检查BUFFSIZE之类的内容时会有所帮助。 但是,请注意strlen()只能用于以空字符结尾的字符串。