没有版本的std::getline()
它接受一个std::string
,或参照std::string
,作为其“分隔符”参数。
Considering only the version which takes a delimiter, the function std::getline()
is declared as follows:
// Version 1a.
template< class CharT, class Traits, class Allocator >
std::basic_istream<CharT,Traits>& getline(std::basic_istream<CharT,Traits>& input,
std::basic_string<CharT,Traits,Allocator>& str,
CharT delim);
// Version 1b (C++11 or later).
template< class CharT, class Traits, class Allocator >
std::basic_istream<CharT,Traits>& getline(std::basic_istream<CharT,Traits>&& input,
std::basic_string<CharT,Traits,Allocator>& str,
CharT delim);
对于std::string
,声明是这样的:
// Version 1a.
std::istream& getline(std::istream& input, std::string& str, char delim);
// Version 1b.
std::istream& getline(std::istream&& input, std::string& str, char delim);
注意,第三个参数是char
。因此,您的分隔符必须是单个字符,而不是字符串。
考虑到这一点,如下我们可以重写代码:
char first_operator, second_operator;
std::cout << "Please enter the first seperation operator :";
std::cin >> first_operator; // Get first character from input.
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // Ignore the rest.
std::cout << "Please enter the second seperation operator :";
std::cin >> second_operator; // Get first character from input.
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // Ignore the rest.
string first_name;
std::cout << "Please enter your name:";
getline(cin, first_name, first_operator);
string last_name;
getline(cin, last_name, second_operator);
std::cout << first_name << " " << last_name << std::endl;
std::cin.ignore();
注意,这仅允许单字符分隔符。如果你想允许多字符分隔符,你需要做更复杂的处理。
std::string first_operator, second_operator;
std::cout << "Please enter the first seperation operator :";
std::getline(std::cin, first_operator);
std::cout << "Please enter the second seperation operator :";
std::getline(std::cin, second_operator);
// Loop until name is entered correctly.
bool done = false;
do {
std::string name_buf;
std::cout << "Please enter your name:";
std::getline(std::cin, name_buf);
auto first_op = name_buf.find(first_operator);
auto second_op = name_buf.find(second_operator);
if (first_op == std::string::npos || second_op == std::string::npos) {
std::cout << "Please separate your first and last names with the first specified operator, "
<< "and follow your last name with the second specified operator.\n";
continue; // Restart loop.
}
first_name = name_buf.substr(0, first_op);
auto last_start = first_op + first_operator.size();
last_name = name_buf.substr(last_start, second_op - last_start);
done = true;
} while(!done);
看到它在行动here。忽略“请输入x”这几行的格式问题,这是由于Ideone如何处理示例代码中的标准输入引起的。
姓名取自xkcd。
谢谢@Justin时间。我会尝试一下,但我对我来说仍然非常复杂。 – Gill
不客气。第二个版本将整个名称读取为单个字符串,然后在其中查找分隔符,以便将字符串分隔为两个名称。 –