0

Exercise:

Define a string object with name numbersLog and one integer variable enteredNr.

Ask the user 3 times to enter an integer value and each time capture the entered value in enteredNr (replacing previous value!)

** Meanwhile use string concatenation to keep a log of the 3 entered numbers in numbersLog.**

Display this log in the console.

This is what I did so far. I don't know how to keep log of the entered numbers in the string.

    std::string numbersLog;
    int enteredNr{};
    std::cout << "Enter an integer value: " << std::endl;
    std::cin >> enteredNr;
    std::cout << "Enter an integer value: " << std::endl;
    std::cin >> enteredNr;
    std::cout << "Enter an integer value: " << std::endl;
    std::cin >> enteredNr;
Alan Birtles
  • 32,622
  • 4
  • 31
  • 60
  • Additionally, you cannot use `std::cin` correctly unless you ***check the stream state*** to know whether a numeric value was entered or the user did something dumb like typing `"twenty-seven"` (or some other stream or conversion error occurred). Perhaps `if (!(std::cin >> enteredNR)) { std::cerr << "error: invalid integer value; return 1; }`? – David C. Rankin Dec 01 '22 at 15:01

1 Answers1

1

Seems like you are not sure how to convert an integer to a string. std::to_string is the easy way to do that, or maybe you don't know how to append one string to another, += is one way to do that.

std::string numbersLog;
int enteredNr;
std::cout << "Enter an integer value: " << std::endl;
std::cin >> enteredNr;
numbersLog = std::to_string(enteredNr);
std::cout << "Enter an integer value: " << std::endl;
std::cin >> enteredNr;
numbersLog += std::to_string(enteredNr);
std::cout << "Enter an integer value: " << std::endl;
std::cin >> enteredNr;
numbersLog += std::to_string(enteredNr);

If you don't know how to do these things that's fine. But one thing you should develop is the ability to look things up. Both these techniques are simple and easily found from a number of different sites.

john
  • 85,011
  • 4
  • 57
  • 81