我必须编写一个程序,从键盘读取一行数字并将它们保存到一个数组中,数字必须写成一行,我写了这个但由于无限循环而无法工作建议?
int main() {
int numCasos = 0, contNumCasos = 0, numElem = 0;
string aux;
cout << "Number of cases: " << endl;
cin >> numCasos;
while (contNumCasos < numCasos) {
cout << "Number of elements: " << endl;
cin >> numElem;
cout << "Enter the Elements separated by space: " << endl;
cin.ignore();
vector.cont = 0;
int i = 0;
while ((vector.cont < numElem) && getline(cin,aux,' ')){
vector.v[i] = stoi(aux);
vector.cont++;
i++;
}
}
cout << sumaBuenos(vector) << endl;
cin.ignore();
system("pause");
return 0;
}
一个例子:
控制台:元素数量:
用户:4
控制台:输入按空格分隔的元素:
用户:2 43 65 56
- 这必须是矢量
- vector.v [0] = 2
- vector.v [1] = 43
- vector.v [2] = 65
- vector.v [3] = 56
答案 0 :(得分:0)
通过修改可行。
int main() {
int numCasos = 0, contNumCasos = 0, numElem = 0;
string aux;
cout << "Numero de casos: " << endl;
cin >> numCasos;
while (contNumCasos < numCasos) {
cout << "Numero de elementos: " << endl;
cin >> numElem;
cout << "Ingrese los elementos separados por espacios: " << endl;
cin.ignore();
vector.cont = 0;
getline(cin, aux);
istringstream iss(aux);
for (int i = 0;i < numElem;i++) {
iss >> aux;
vector.v[i] = stoi(aux);
vector.cont++;
}
cout << sumaBuenos(vector) << endl;
contNumCasos++;
}
system("pause");
return 0;
}
遇到同样问题的人。
答案 1 :(得分:0)
如果你知道你需要阅读多少个数字,那么有一个更简单的方法:
int n;
cin>>n; // how many numbers;
vector<int> v(n);
for ( int i=0; i<n; ++i ){
cin>>v[i];
}
答案 2 :(得分:0)
#include<iostream>
using namespace std;
int main()
{
int n;
cout << "input numbers" << endl;
cin >> n;
vector<int> v(n);
for ( int i=0; i<n; ++i )
{
cin >>v[i];
}
return 0;
}
答案 3 :(得分:-1)
#include <bits/stdc++.h>
#include<iostream>
using namespace std;
int main()
{
int sizeofarray;
cin >> sizeofarray;
int a[sizeofarray];
int i;
for (i = 0; i < sizeofarray; ++i)
{
cin >> a[i];
}
return 0;
}