c++ - scanf() 只取数组的第一个整数
问题描述
我正在编写一个程序来对用户输入的数组进行排序。以下代码需要输入 8 个个位整数,然后放入数组中。
#include <iostream>
#include <stdio.h>
using namespace std;
void printArray(int ary[], int n) {
cout << "The sequence you entered is as follows:" << endl;
for (int i=0; i<n; i++) {
cout << ary[i] << " ";
}
cout << "\n";
}
int main() {
using namespace std;
int nums[8];
cout << "Please enter 8 single digits between 1 and 9" << endl;
for(int k=0; k<8; k++) {
scanf("%d", &nums[k]);
}
printArray(nums, 8);
cout << endl;
return 0;
}
但是当我输入数字时,只有第一个整数被推入数组,其余为 0。例如,当输入是:
2,5,7,2,1,4,6,8
. 输出是:2 0 0 0 0 0 0 0
解决方案
您应该使用的输入语法是这样的:2 5 7 2 1 4 6 8
。或者您可以更改scanf("%d", &nums[k]);
为scanf("%d,", &nums[k]);
,现在您可以输入2,5,7,2,1,4,6,8