I got a problem. I need to allow a user to make one input and it assigns the numbers to variables. Afterwards, it computes the sum. So if I input "1 2 3", it will output 6. How do i go about assigning the variables the values if cin only can affect one?
One possible option is to obtain the input as one string, and then split it into numbers delimited by the whitespace between them.
If you don't wish to use stringstreams, you can parse the input string yourself (character by character).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include <iostream>
#include <string>
#include <sstream>
int main()
{
std::string input;
std::getline(std::cin, input); // get whole line entered as input
std::istringstream iss(input); // convert input to a stringstream
int num;
while (iss >> num) // get each number out of the input string's stream
{
std::cout << "You entered: " << num << '\n';
// TODO: Keep track of a "sum" variable.
}
}
Hint: You can edit your post, highlight your code and press the <> formatting button.
You can use the preview button at the bottom to see how it looks.
Note that the program fails when you type non digits. 🙂
Do read handy andys post. Though I think it was a little harsh to ask you to work this out yourself.
Since its certain to be three inputs there's no need to use stringstream
You could either take input with cin and three string and convert the string or you could take input with three integers and check for fail state, which is what I would have done.
But more importantly cin is an easier and shorter approach. Consider that OP is probably a newbie.
Then it's more important to know about cin than stringstream.
Lol I found that really funny XD. I love you for that reply bulba!
But you're right last chance. Bulba sheen i don't want you to go wrong because of me. So use cin only if it is guaranteed that there are only 3 inputs.
Otherwise If you know only that the number input is terminated with newline then you must use get line (and hence stream) Because cin doesn't read whitespace so you've got no choice. 👍