【问题标题】:C++ - inputting and outputting multiple integers with io redirectionC++ - 使用 io 重定向输入和输出多个整数
【发布时间】:2016-10-01 15:22:32
【问题描述】:

我是 C++ 新手,正在编写一个简单的程序,该程序应该从文件中获取整数作为整数,并以适当的格式输出它们。问题是程序在输出时跳过了其中一个值。例如(\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 */
    }
}

【问题讨论】:

  • 您没有将n 写入cout 的代码。
  • @RSahu 你这是什么意思?
  • 您正在使用while ( cin &gt;&gt; n ) 将数字读入n。该号码未写入cout

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


【解决方案1】:

您的 while 循环条件:while(cin &gt;&gt; n) 将尝试在变量 n 中存储一个整数,如果 cin &gt;&gt; n 成功则返回 true,从而允许您进入循环。如果您的所有数据都在一个文件中并且您没有使用数组/向量来遍历文件以获取文件,那么我真的不明白使用循环的意义。使用数组会很有效,例如:

int values[NUMBER_OF_ELEMENTS]; // if number of elements is known
std::vector<int> values;// Use vector otherwise

在任何情况下,删除您的 while 循环条件以及与之关联的大括号,您的代码应该会按预期运行。

【讨论】:

    【解决方案2】:

    问题一:

    您正在使用while ( cin &gt;&gt; n ) 将数字读入n。该号码未写入cout。这意味着,第一个数字被读取并丢弃。

    问题 2:

    cin &gt;&gt; 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;
    }
    

    【讨论】:

    • 谢谢你,工作,你的回答让我明白了这一点:while (cin &gt;&gt; n ) { if (n &lt; 0) {cout &lt;&lt; "-";} else {cout &lt;&lt; "+";} cout &lt;&lt; setw(10); cout &lt;&lt; abs(n) &lt;&lt; "\r\n"; }
    • @Bobbis,很高兴我能提供帮助。
    猜你喜欢
    • 1970-01-01
    • 2013-04-17
    • 2018-08-05
    • 1970-01-01
    • 1970-01-01
    • 2016-03-10
    • 2013-03-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多