3

我需要从控制台读取输入并将其放入一个字符数组中。我编写了以下代码,但出现以下错误:“分段错误”

#include <stdio.h>
#include <stdlib.h>

int main() {

    char c;
    int count;
    char arr[50];

    c = getchar();
    count = 0;
    while(c != EOF){
        arr[count] = c;
        ++count;
    }


    return (EXIT_SUCCESS);

}
4

3 回答 3

9
#include <stdio.h>
#include <stdlib.h>
int main() {
    char c;                /* 1. */
    int count;
    char arr[50];
    c = getchar();         /* 2. */
    count = 0;
    while (c != EOF) {     /* 3. and 6. and ... */
        arr[count] = c;    /* 4. */
        ++count;           /* 5. */
    }
    return (EXIT_SUCCESS); /* 7. */
}
  1. c应该是一个int。getchar() 返回一个 int 来区分有效字符和 EOF
  2. 读一个字符
  3. 将该字符与 EOF 进行比较:如果不同则跳转到 7
  4. 将该字符放入数组arr元素中count
  5. 准备将“另一个”字符放入数组的下一个元素中
  6. 检查在 1. 读取的字符是否为 EOF

每次循环都需要读取不同的字符。(3., 4., 5.)

并且您不能在数组中放置比您保留的空间更多的字符。(4.)

尝试这个:

#include <stdio.h>
#include <stdlib.h>
int main() {
    int c;                 /* int */
    int count;
    char arr[50];
    c = getchar();
    count = 0;
    while ((count < 50) && (c != EOF)) {    /* don't go over the array size! */
        arr[count] = c;
        ++count;
        c = getchar();     /* get *another* character */
    }
    return (EXIT_SUCCESS);
}

编辑

在数组中有字符后,您会想要对它们做点什么,对吧?因此,在程序结束之前,添加另一个循环来打印它们:

/* while (...) { ... } */
/* arr now has `count` characters, starting at arr[0] and ending at arr[count-1] */
/* let's print them ... */
/* we need a variable to know when we're at the end of the array. */
/* I'll reuse `c` now */
for (c=0; c<count; c++) {
    putchar(c);
}
putchar('\n'); /* make sure there's a newline at the end */
return EXIT_SUCCESS; /* return does not need () */

请注意,我没有使用字符串函数 printf()。我没有使用它,因为arr它不是字符串:它是一个纯字符数组,没有(必然)有 0(NUL)。只有其中带有 NUL 的字符数组才是字符串。

要将 NUL 放入 arr,而不是将循环限制为 50 个字符,而是将其限制为 49(为 NUL 保留一个空格)并在末尾添加 NUL。在循环之后,添加

arr[count] = 0;
于 2009-09-10T20:48:14.267 回答
6
#include <stdio.h>
#include <stdlib.h>

int main() {

    int c;
    int count;
    int arr[50];

    c = getchar();
    count = 0;
    while( c != EOF && count < 50 ){
        arr[count++] = c;
        c = getchar();
    }


    return (EXIT_SUCCESS);

}

注意 while 循环中的&& count < 50。如果没有这个,您可能会超出 arr 缓冲区。

于 2009-09-10T20:14:34.957 回答
4

我有一个小建议。
而不是在程序中有c = getchar();两次,
修改while循环如下,

while( (c = getchar()) != EOF && count < 50 ){
        arr[count++] = c;
}
于 2012-06-30T20:09:37.637 回答