[英]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. */
}
c
应该是一个int。 getchar()返回一个int来区分有效字符和EOF arr
,元素count
每次循环都需要读取不同的字符。 (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.