0

I am new to C++ programming and am trying to create a program that asks the user questions. For example,

std::string siblings;
std::cout << "How many siblings do you have?";  //Let's say the user inputs 2
std::cin >> siblings;

for (int x=0;x<n;x++){
    std::string current;
    std::string sibling_info;
    std::cout << "What is the name + age of sibling #" << (x+1) << ": ";
    std::cin >> current;                    
    sibling_info.emplace_back(current);

I want the user to input "John 13" with a space in between, but whenever I put a space the program does not run the way I want it to and doesn't ask the user twice.

Kara
  • 765
  • 5
  • 11
  • 29
  • `std::getline(std::cin, current);` but you still have to parse the name from the number somewhere - you don't show us that code though – user3125280 Jan 19 '14 at 07:18
  • The same question: http://stackoverflow.com/questions/5838711/c-cin-input-with-spaces – Igor Jan 19 '14 at 07:20

3 Answers3

1

input from cin is white space delineated which includes spaces. std::cin >> current stores only the first word which was typed. In order to get two words you'd have to call cin twice, or switch to a different way of getting user input.

std::string current;
std::string age;
std::string sibling_info;
std::cout << "What is the name + age of sibling #" << (x+1) << ": ";
std::cin >> current; //you were missing a semicolon :p
std::cin >> age;    //added
current += " " + age;      //added       
sibling_info.emplace_back(current);

or using getline (you need to #include<string>)

std::string current;
std::string sibling_info;
std::cout << "What is the name + age of sibling #" << (x+1) << ": ";
current = getline(cin,current); //changed                      
sibling_info.emplace_back(current);
Alex
  • 1,388
  • 1
  • 10
  • 19
1

One way to do it:

std::string current[2];
...
std::cin >> current[0] >> current[1];
sibling_info.emplace_back(current[0]+" "+current[1]);
barak manos
  • 29,648
  • 10
  • 62
  • 114
1

Function emplace_back() can be used for vector, but not for string. So you need to change

std::string sibling_info;

to

std::vector<std::string> sibling_info;

Then you can call:

sibling_info.emplace_back(current);

At the same time, it will enable you to input any number of multiple inputs.

Check out here for more info.

herohuyongtao
  • 49,413
  • 29
  • 133
  • 174