好的,我想这就是你想要的:
#include <iostream>
#include <string>
#include <vector>
#include <boost/algorithm/string.hpp>
using namespace std;
int main()
{
// Read a line from stdin
string line;
getline(cin, line);
vector<string> str_vec;
boost::split(str_vec, line, boost::is_any_of(" ,"));
if (str_vec.size() == 3) {
string last = str_vec[0];
string first = str_vec[1];
string middle = str_vec[2];
std::cout << "First=" << first << " Last=" << last << " Middle=" << middle << endl;
}
}
如果您不想使用(或没有)boost 库,您可以检查以下版本。注释应该可以帮助您理解代码的每个块。
#include <iostream>
#include <string>
using namespace std;
int main()
{
// Read a line from stdin
string line;
getline(cin, line);
// Erase all commas
while (true) {
size_t comma_pos = line.find(",");
if (comma_pos != std::string::npos) {
line.erase(comma_pos, 1);
line.insert(comma_pos, " ");
}
else break;
}
// Change all two spaces to only one space
while (true) {
size_t space_pos = line.find(" ");
if (space_pos != std::string::npos)
line.erase(space_pos, 2);
else break;
}
// Tokenize the names
size_t end_last_pos = line.find(" ");
if (end_last_pos == string::npos) {
cout << "Missing last name" << endl;
return 1;
}
string last = line.substr(0, end_last_pos);
size_t end_first_pos = line.find(" ", end_last_pos + 1);
if (end_first_pos == string::npos) {
cout << "Missing first name" << endl;
return 1;
}
string first = line.substr(end_last_pos + 1, end_first_pos - end_last_pos - 1);
size_t end_middle_pos = line.find(" ", end_first_pos + 1);
string middle;
if (end_middle_pos == string::npos)
middle = line.substr(end_first_pos + 1);
else
middle = line.substr(end_first_pos + 1, end_middle_pos - end_first_pos - 1);
// Print the names
std::cout << "First='" << first << "' Last='" << last << "' Middle='" << middle << "'" << endl;
}