我正在尝试创建一个C程序,该程序读取标准输入,直到到达输入结束为止,然后将偶数存储到数组中并打印出来。 我不知道为什么我的程序无法按预期运行。任何帮助将不胜感激。
#include <stdio.h>
int main(){
int num = getchar();
int list[10000];//array to store even nums
int i = 0;
while(num != EOF){
if(num % 2 == 0){
list[i] = num;//store even nums
i++;
}
num = getchar();
}
for(int j = 0;j < i;j++){
printf("%d ",list[j]);
}
return 0;
}
//example output from terminal
Test 8 (1 1 2 3 5 8 13 21 34) - failed (Incorrect output)
Your program produced these 1 lines of output:
10 10 50 10 10 10 56 10 10 50 10 52 10
Last line of output above was not terminated with a newline('\n') character
The correct 1 lines of output for this test were:
2 8 34
The difference between your output(-) and the correct output(+) is:
- 10 10 50 10 10 10 56 10 10 50 10 52 10
+ 2 8 34
The input for this test was:
1
1
2
3
5
8
13
21
34
答案 0 :(得分:3)
如果仅输入一行,则不必存储所有数字,只需打印它们即可:
#include <stdio.h>
int main(void)
{
int num;
while (scanf("%d", &num) == 1) {
if(num % 2 == 0)
printf("%d ", num);
}
putchar('\n'); // from your output it is clear that
// a newline at the end is expected.
return 0;
}
如果您必须处理多行:
#include <stddef.h>
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
size_t capacity = 0;
int *numbers = NULL;
size_t count = 0;
int input;
while (scanf("%d", &input) == 1) {
if(input % 2 == 0) {
if(count == capacity) {
capacity += 10;
numbers = realloc(numbers, capacity * sizeof(int));
}
numbers[count++] = input;
}
}
for(size_t i = 0; i < count; ++i)
printf("%d ", numbers[i]);
putchar('\n');
free(numbers);
return 0;
}
答案 1 :(得分:2)
getchar()
一次只能读取一个char
,您需要使用一个读取完整输入的函数。
scanf("%d", &num);
或更好的fgets
和strtol
:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define N 10000
int main(void)
{
int list[N];
int num, i = 0;
char buf[32], *ptr;
while ((i < N) && fgets(buf, sizeof buf, stdin)) {
if (buf[0] == '\n') {
break;
}
num = (int)strtol(buf, &ptr, 10);
if (*ptr != '\n') { // not a valid number
continue;
}
if (num % 2 == 0) {
list[i] = num; //store even nums
i++;
}
}
for (int j = 0; j < i; j++) {
printf("%d ", list[j]);
}
printf("\n");
return 0;
}