将用户输入放入字符数组(C 编程)
我需要从控制台读取输入并将其放入字符数组中。我编写了以下代码,但出现以下错误:“分段错误”
#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);
}
I need to read the input from the console and put it into an array of chars. I wrote the following code, but I get the following error: "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);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
c
应该是一个 int。 getchar() 返回一个 int 来区分有效字符和 EOFarr
,元素count
每次循环都需要读取不同的字符。 (3., 4., 5.)
并且您在数组中放置的字符不能多于您保留的空间。 (4.)
试试这个:
编辑
在数组中拥有字符后,您会想要对它们做一些事情,对吧?因此,在程序结束之前,添加另一个循环来打印它们:
注意我没有使用字符串函数 printf()。我没有使用它,因为 arr 不是字符串:它是一个普通的字符数组,(不一定)有 0(NUL)。只有其中包含 NUL 的字符数组才是字符串。
要将 NUL 放入 arr 中,不要将循环限制为 50 个字符,而是将其限制为 49 个(为 NUL 保留一个空格)并在末尾添加 NUL。循环后添加
c
should be an int. getchar() returns an int to differentiate between a valid character and EOFarr
, elementcount
You need to read a different character each time through the loop. (3., 4., 5.)
And you cannot put more characters in the array than the space you reserved. (4.)
Try this:
Edit
After you have the characters in the array you will want to do something to them, right? So, before the program ends, add another loop to print them:
Notice I didn't use the string function printf(). And I didn't use it, because
arr
is not a string: it is a plain array of characters that doesn't (necessarily) have a 0 (a NUL). Only character arrays with a NUL in them are strings.To put a NUL in arr, instead of limiting the loop to 50 characters, limit it to 49 (save one space for the NUL) and add the NUL at the end. After the loop, add
注意&&计数< while 循环中的 50。如果没有这个,你可能会溢出 arr 缓冲区。
Notice the && count < 50 in the while loop. Without this you can overrun the arr buffer.
我有一个小建议。
而不是在程序中使用两次
c = getchar();
,修改while循环如下,
I have a small suggestion.
Instead of having
c = getchar();
twice in the program,modify the while loop as follows,