将用户输入放入字符数组中(C编程)

4

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

#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);

}

如果我想在循环中打印当前字符并添加以下内容:printf(arr[count]);我再次遇到分段错误。 - user69514
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 应该是一个整数。getchar() 返回一个整数以区分有效字符和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的字符数组才是字符串。
要在arr中放置一个NUL,而不是将循环限制在50个字符,将其限制在49个字符(留出一个空间给NUL),并在结尾处添加NUL。在循环后,添加
arr[count] = 0;

说句题外话,与其在一个循环中使用putchar(),最好直接使用fwrite(arr,1,count,stdout) - Chris Lutz
有没有一种方法可以动态分配数组的大小?(如果输入数量未知) - NGix
@Ir0nm:是的。你可以在循环中使用realloc()来根据需要不断扩展数组。 - pmg

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。没有这个条件,可能会导致数组缓冲区溢出。


哈,那很简单。抱歉,我是C语言的新手,这是我的第一个程序。谢谢。 - user69514
在循环中仍然需要“c = getchar();”才能使其正常工作。 - Andrew Bainbridge

4

我有一个小建议。
在程序中不要两次使用c = getchar();
可以将while循环修改如下:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接