我是 C++ 的新手,正在编写一个简单的程序,该程序应该从文件中获取整数作为 int 并以适当的格式输出它们。问题是程序在输出时跳过了其中一个值。例如(\n 表示换行)“51 123\n -10\n 153 111”将显示为“123\n -10\n 153\n 111\n 0”。此外,任何改进我的代码的提示或指示都会很棒。 这是我的代码:
using namespace std;
int main(int argc, char *argv[]) {
size_t i;
int n;
int a, b, c, d, e;
if (argc == 1) {
while (cin >> n) {
cin >> a;
cin >> b;
cin >> c;
cin >> d;
cin >> e;
cout << setw(10);
cout << a << "\r\n";
cout << setw(10);
cout << b << "\r\n";
cout << setw(10);
cout << c << "\r\n";
cout << setw(10);
cout << d << "\r\n";
cout << setw(10);
cout << e;
}
} else if (strcmp(argv[1],"-x")==0) {
/* not used yet */
} else if (strcmp(argv[1],"-o")==0) {
/* not used yet */
}
}
最佳答案
问题一:
您正在使用 while ( cin >> n )
将数字读入 n
。该数字未写入 cout
。这意味着,第一个数字正在被读取并丢弃。
问题2:
行 cin >> e;
并没有真正将任何内容读入 e
。这就是输出中有 0
的原因。
建议修复:
读取while
条件中的所有数字。
while (cin >> a >> b >> c >> d >> e)
{
cout << setw(10);
cout << a << "\r\n";
cout << setw(10);
cout << b << "\r\n";
cout << setw(10);
cout << c << "\r\n";
cout << setw(10);
cout << d << "\r\n";
cout << setw(10);
cout << e;
}
关于C++ - 使用 io 重定向输入和输出多个整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37582538/