How to read names with space?

…衆ロ難τιáo~ 提交于 2021-02-19 06:14:57

问题


If I have the data look like this:

Michael 30
Tom 35

I can handle it by the following code:

#include <iostream>
#include <string>
int main()  {
    std::string name;
    int age;
    while(std::cin >> name >> age)  {
        std::cout << name << " is " << age << " years old." << std::endl;
    }
    return 0;
}

However if my data looks like this:

Michael Corleone
30
Tom Hagen
35

I tried using this code, but it only read the first line, the logic seems that it should read all the lines, so I don't know why this attempt fails.

#include <iostream>
#include <string>
int main()  {
    std::string name;
    int age;
    while(std::getline(std::cin, name) && std::cin >> age)  {
        std::cout << name << " is " << age << " years old." << std::endl;
    }
    return 0;
}

Even worse, if my data look like this:

Michael Corleone 30
Tom Hagen 35

Follow the suggestion by one of the answers, I can have a workaround by splitting the name into name1 and name2:

int main()  {
    std::string name1, name2;
    int age;
    while(std::cin >> name1 >> name2 >> age)  {
        std::cout << name1 + ' ' + name2 
            << " is " << age << " years old." << std::endl;
    }
    return 0;
}

However, this is not nice, what if someone have a middle name for example?


回答1:


Looking at the second example with this data:

Michael Corleone
30
Tom Hagen
35

The problem is that after reading the age with std::cin >> age the end-of-line character is still left in the stream so the following std::getline gets nothing because it thinks the line is empty (which it is).

The trick is to skip whitespace before reading each new record:

std::string name;
int age;
while(std::cin >> std::ws && std::getline(std::cin, name) && std::cin >> age) {
    std::cout << name << " is " << age << " years old." << std::endl;
}

Or, more succinctly:

std::string name;
int age;
while(std::getline(std::cin >> std::ws, name) >> age) {
    std::cout << name << " is " << age << " years old." << std::endl;
}



回答2:


How about this?

#include <iostream>
#include <string>
    int main()  {
        std::string firstname;
        std::string lastname;
        int age;
        while(true){
          std::cin >> firstname;
          std::cin >> lastname;
          std::cin >> age);
          std::cout << firstname << " " << lastname << " is " << age << " years old." << std::endl;
        }
        return 0;
    }


来源:https://stackoverflow.com/questions/39881604/how-to-read-names-with-space

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!