Home > OS >  how to make multiple output from one input
how to make multiple output from one input

Time:11-21

#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
}

if i run the code above, example input 1 y 7 y 5 n, the output of the code will only appear last number i input, how do i make them all printed out in cout ? dont tell me to make new variable with different name.

CodePudding user response:

According to the limitation you specified, we cannot make new variables. Then we use what we have.

We repurpose repeat to store the resulting string that will be the printed answer.

The "repeat" question now has an integer output so we don't waste a string variable on it. It sounds as "repeat?(1 - yes / 0 - no)".

We repurpose input2 to be a stop flag. If the "repeat?" question is answered as 0 or a string, the cycle stops.

#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;
}

After that, the console log can look roughly like this:

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

If you get an error about std not having to_string(), add #include<string> to the program. (link to the issue)

CodePudding user response:

the output of the code will only appear last number i input, how do i make them all printed out in cout ?

Just move the cout statement inside the while loop as shown below:

#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
}

The program now output/print all entered numbers(inputs) as you want which can be seen here.

  • Related