1
#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.

4
  • im changing the question, sorry for that Commented Nov 20, 2021 at 13:47
  • 1
    You can have a vector<string> inputs; and then inputs.push_back(input1); after reading it in, then for (auto&& s : inputs) cout << s << "\n"; to output them all. Commented Nov 20, 2021 at 13:51
  • Replace with vector<int> inputs; for integers. Commented Nov 20, 2021 at 13:52
  • 1
    This doesn't address the question, but while (repeat.compare("n") != 0) really should be written while (repeat != "n"). Commented Nov 20, 2021 at 14:03

2 Answers 2

1

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)

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.