C++ - 使用 io 重定向输入和输出多个整数

标签 c++ while-loop io io-redirection

我是 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/

相关文章:

Python:被要求输入两次并输出重复的打印语句

java - 线程停止执行

c++ - 如何在opencv中使用SIFT

当我用单引号括起一个字符串时,C++ std::cout 打印奇怪的字符

python - 在Python循环中计算余额和每月付款

scala - 设计从 channel 读取的引用透明函数

python - 转换为 TextIOWrapper 的 BytesIO 对象没有 fileno 属性。

c++ - 在 C++ 中以图形方式为图形绘制顶点

c++ - 函数参数 : accepting a null value also

shell - 在循环时跳过一行并在 shell 脚本中读取另一行