Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/55.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为什么这段代码会给我运行时错误?C_C - Fatal编程技术网

为什么这段代码会给我运行时错误?C

为什么这段代码会给我运行时错误?C,c,C,我不明白为什么它总是给出运行时错误:/What's write?我如何解决这个问题? 这是我的密码: #include <stdio.h> int main() { int i=0, ch; char word[100]; for(;(ch = getc(stdin)) != EOF;) { do{ word[i] = ch; if(ch == 32) word[i] = '\0';

我不明白为什么它总是给出运行时错误:/What's write?我如何解决这个问题? 这是我的密码:

#include <stdio.h>

int main() 
{
    int i=0, ch;
    char word[100];
    for(;(ch = getc(stdin)) != EOF;)
    {
        do{
            word[i] = ch;
            if(ch == 32) word[i] = '\0';
            i++;
        } while(ch != 32);

    }
    printf("%s", word);
    return 0;
}

#包括
int main()
{
int i=0,ch;
字符字[100];
对于(;(ch=getc(stdin))!=EOF;)
{
做{
字[i]=ch;
如果(ch==32)字[i]='\0';
i++;
}而(ch!=32);
}
printf(“%s”,单词);
返回0;
}
第一次按键时,缓冲区溢出。这应该指出一个更广泛的问题,除了这段代码之外,没有范围检查的固定大小缓冲区

在此循环中:

    do{
        word[i] = ch;
        if(ch == 32) word[i] = '\0';
        i++;
    } while(ch != 32);
ch
的值永远不会改变,因此有一个无限循环。因此,您也会通过缓冲区
word
的末尾进行写入,因为
i
会无限制地增加,调用

这里不需要两个循环。只需检查EOF和空间。此外,您应该使用字符常量
'
来表示空格,而不是其ASCII代码

for (i=0; ((ch = getc(stdin)) != EOF) && (ch != ' '); i++)
{
    word[i] = ch;
    if(ch == ' ') word[i] = '\0';
}

请说明您看到的错误。运行时错误#stdin#stdout 0s 4524kb请完成此操作。第一个字符是什么,比如说,
A
?不管我输入什么,它都会给我运行时错误:/Hint:
ch
在内部循环中永远不会改变如果他只输入一个字符,后跟32,那么@hacker315他们将永远找不到32,因为getch在外部循环中。
for (i=0; ((ch = getc(stdin)) != EOF) && (ch != ' '); i++)
{
    word[i] = ch;
    if(ch == ' ') word[i] = '\0';
}