繁体   English   中英

将用户输入放入char数组(C编程)

[英]Putting user input into char array (C Programming)

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

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

}
#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;
#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缓冲区。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM