简体   繁体   中英

Trying to extract three names from one line using getline

Hi there I'm learning C++ and I'm trying to extract three names (first, middle, last) from one line.

cout<< "Please enter your full name" << endl;
  getline(cin, first_name, ' ');
  getline(cin, midLast_name);

I take the middle and last name as variable and then split them up. I need to be able to accept a space as a middle name so this is what I'm doing. However, in my conditional statement, the code isn't finding a space even though there is one. Any ideas?

if (midLast_name.find(" ") == true)
{
    first_space = midLast_name.find(" ");
    middle_name = midLast_name.substr(0,first_space);
    last_space = midLast_name.rfind(" ");
    last_name = midLast_name.substr(midLast_name.rfind(" ") + 1, full_name.length());

 } 

string::find(...) returns the position or string::npos if not found, thus your code should compare against npos rather than ==true .

size_t firstspace = midLast_name.find(" ");
if (firstspace != string::npos) {
   middle_name= midLast_name.substr(0, firstspace);
   ... 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM