Problems with cin not picking up all strings?

I'm trying to write code that can get input from a user. The input will be something like "1 empty container" or "5 fish", etc. Basically a number followed by one or more strings. Here is my code:

1
2
3
4
cout << "Enter the input: ";
double numberofitems;
string itemname;
cin >> numberofitems >> itemname;


The problem I'm having is that itemname seems to only pick up the first string. Is there a way to set it equal to the entire string, possibly including spaces?
The >> operator for std::cin is delimited by whitespace, meaning it will parse your number until a space, then try to parse itemname until a space, and then not actually parse your third item.

If you want to get user input with spaces, you must use std::getline

1
2
3
4
5
6
7
8
#include <iostream>
#include <string>
int main()
{
    std::string itemname;
    std::getline(std::cin, itemname);
    std::cout << "You typed: " << itemname << "\n";
}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <string>
int main()
{
    double num_items;
    std::cin >> num_items;

    // Clear the extra space after entering the number
    std::cin >> std::ws;

    std::string itemname;
    std::getline(std::cin, itemname);

    std::cout << "You typed: " << num_items << " " << itemname << "\n";
}
Last edited on
Hello All,

As I have learned over time and the hard way Ganado's line 112 can be written as std::getline(std::cin >> std::ws, itemname); and it replaces line 9,

Just an FYI.

Andy
Topic archived. No new replies allowed.