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?
If you put a space in your input, between the number and the item name, you should get what you want.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <string>

using namespace std; 

int main()
{
	double numberOfItems;
	string itemName;
	
	cout << "\nEnter number of items and item name separated by a space\n";
	cin >> numberOfItems >> itemName;
	
	cout << "\nNumber of items: " << numberOfItems
		<< "\nItem name: " << itemName
		<< "\n\n";
	
	return 0;
}


intput:
20 rock


output:
Number of items: 20
Item name: rock


EDIT: if you want your item name string to be composed of more than one word, you can use the std::getline() function like so:
1
2
cin >> numberOfItems;
getline(cin, itemName);


hope this helps!
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <string>
#include <iomanip>

int main()
{
    std::cout << "enter number of items and item name: " ;

    int number_of_items ;
    std::string item_name ;

    // read number_of_items, skip leading white space (with std::ws),
    // and then read everything up to the new line into item_name (with std::getline)
    if( std::cin >> number_of_items >> std::ws && std::getline( std::cin, item_name ) )
    {
        std::cout << "#items: " << number_of_items
                  << "\nitem name: " << std::quoted(item_name) << '\n' ;
    }

    else std::cerr << "invalid input\n" ;
}
Topic archived. No new replies allowed.