Reputation: 43
I am new to C++ and I want the user to input a set of data followed by spaces like this:
Mark 23 California, USA
Susan 22 Tokyo, Japan
Anna 21 New Mexico, USA
I am not sure how to gather all of these separate information. I want to categorize them by name, age, location so I can access them later on by using (age[0]. age[1], etc)
So far, this is what I have
std::vector<std::string> name, age, location:
std::cout << "Hello, what is your Name Age Location? (separate by space) ";
std::string a, b, c;
std::cin >> a;
std::cin >> b;
std::cin >> c;
a.push_back(name);
b.push_back(age);
c.push_back(location);
std::cout << "How many people would you like to store their data? ";
int n;
std::cin >> n;
for (int a=0;a<n;a++){
std::cout << "Please enter the Name Age Location for Person #" << n << ": ";
std::string x, y, z;
std::cin >> x;
std::cin >> y;
std::cin >> z; //this part always gets me because the location is separated by a space and always gets cut off
x.push_back(name);
y.push_back(age);
z.push_back(location);
}
I want to know how to be able to store the rest of the information after the 2nd white space until the end of the line. Thank you!!
Upvotes: 0
Views: 2876
Reputation:
You read the name and age values as you're doing, but then use std::getline
to get the rest of the line, i.e. the location.
std::cin >> name;
std::cin >> age;
std::getline(std::cin, location); // voila!
Upvotes: 1
Reputation: 2783
std::cin will break the line in general after a space, use std::getline() instead:
char buffer[256];
std::getline(buffer, size(buffer));
Upvotes: 0