输入一个不定长度的数组,要求按回车结束。问题在于第一个就是回车的时候,我用(c = getchar()) == '\n'来判断,没问题。但是第一个如果不是回车,getchar就会吞掉第一个数字。输入的数组就错了。
但如果不写getchar,第一个按回车无法结束,不能跳出循环。
既要满足1.第一个是回车,结束。
2.第一个是数字,不丢失的读入。
怎么办,求指教。
for (int i = 0; i < MaxSize; i++)
{
if ((c = getchar()) == '\n') break;
scanf_s("%d", &a.date[i]);
printf("%d ", a.date[i]);
n++;
}
1 2 3 4
2 3 4
把getchar放到scanf下面去则会导致:若第一个为回车则不会结束,不会跳出循环。
for (int i = 0; i < MaxSize; i++)
{
scanf_s("%d", &a.date[i]);
printf("%d ", a.date[i]);
n++;
if ((c = getchar()) == '\n') break;
}
你不能这么写啊,这样第一个字符丢了啊
scanf_s("%d", &a.date[i]);
if ((c = getchar()) == '\n') break;
break换到下面
对于这种情况,正确做法是先读入一行,然后再从读入的那行里提取数据。下面是C和C++版本例子,你可以参考一下。
C版本
#include <stdio.h>
#define MAX_LINE 256
#define MAX_NUMS 64
int main()
{
// Read a line.
char line[MAX_LINE];
if (!fgets(line, MAX_LINE, stdin))
{
printf("failed to read a line\n");
return 1;
}
// Read numbers from the line.
int a[MAX_NUMS], n = 0, m = 0;
const char *p = line;
while (n < MAX_NUMS && sscanf(p, "%d%n", a + n, &m) > 0)
{
n++;
p += m;
}
// Output the numbers.
for (int i = 0; i < n; i++)
printf("%d ", a[i]);
printf("\n");
return 0;
}
C++版本
#include <iostream>
#include <sstream>
#include <vector>
using namespace std;
int main()
{
// Read a line.
string line;
if (!getline(cin, line)) {
cerr << "failed to read a line\n";
return 1;
}
// Read numbers from the line.
vector<int> a;
int x;
istringstream ss(line);
while (ss >> x)
a.push_back(x);
// Output the numbers.
for (auto x : a)
cout << x << ' ';
cout << endl;
return 0;
}