【问题标题】:how to make multiple output from one input如何从一个输入进行多个输出
【发布时间】:2021-11-20 13:41:22
【问题描述】:
#include <iostream>
using namespace std;
int x, input1, input2;
string repeat;

int main() {
    while (repeat.compare("n") != 0) {
        cout << "input1 : ";
        cin >> input1; //input
        cout << "repeat?(y/n) ";
        cin >> repeat;
    }
    cout << input1; //output
}

如果我运行上面的代码,例如输入 1 y 7 y 5 n,代码的输出只会出现我输入的最后一个数字,我如何让它们全部打印在 cout 中?不要告诉我用不同的名称创建新变量。

【问题讨论】:

  • 我正在更改问题,抱歉
  • 读入后可以有vector&lt;string&gt; inputs;,然后inputs.push_back(input1);,然后for (auto&amp;&amp; s : inputs) cout &lt;&lt; s &lt;&lt; "\n";全部输出。
  • 整数替换为vector&lt;int&gt; inputs;
  • 这并没有解决问题,但while (repeat.compare("n") != 0)确实应该写成while (repeat != "n")

标签: c++ input output


【解决方案1】:

根据您指定的限制,我们无法制作新变量。然后我们使用我们所拥有的。

我们重新利用repeat 来存储将作为打印答案的结果字符串。

“重复”问题现在有一个整数输出,因此我们不会在其上浪费字符串变量。听起来像"repeat?(1 - yes / 0 - no)"

我们将input2 重新用作停止标志。如果“重复?”问题回答为0or a string,循环停止。

#include <iostream>
using namespace std;
int x, input1, input2;
string repeat;

int main() {
    input2 = 1;
    while (input2 != 0) {
        cout << "input1 : ";
        cin >> input1;
        repeat += std::to_string(input1) + " ";
        cout << "repeat?(1 - yes / 0 - no) ";
        cin >> input2;
    }
    cout << repeat;
}

之后,控制台日志大致如下所示:

input1 : 2
repeat?(1 - yes / 0 - no) 1
input1 : 45
repeat?(1 - yes / 0 - no) 1
input1 : 2374521
repeat?(1 - yes / 0 - no) 0
2 45 2374521

如果您收到关于 std 没有 to_string() 的错误,请将 #include&lt;string&gt; 添加到程序中。 (link to the issue)

【讨论】:

    【解决方案2】:

    代码的输出只会出现我输入的最后一个数字,如何让它们全部打印在 cout 中?

    只需将cout 语句移动到while 循环中,如下所示:

    #include <iostream>
    using namespace std;
    int x, input1, input2;
    string repeat;
    
    int main() {
        while (repeat.compare("n") != 0) {
            cout << "input1 : ";
            cin >> input1; //input
            cout << "repeat?(y/n) ";
            cin >> repeat;
            cout << input1; //MOVED INSIDE WHILE LOOP
        }
       // cout << input1; //DONT COUT OUTSIDE WHILE LOOP
    }
    
    

    程序现在可以根据需要输出/打印所有输入的数字(输入),可以看到here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多