沒有版本的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
不客氣。第二個版本將整個名稱讀取爲單個字符串,然後在其中查找分隔符,以便將字符串分隔爲兩個名稱。 –