getline() 中的定界符不能正常工作

delimiter on getline() doesnt work properly

我有一个简单的代码,它使用 getline() public 函数获取用户名作为数组。当它到达 char '$' 时,我想停止从用户那里获取输入并在到达 char'$'(我的定界符)后立即转到下一个 line.but 它忽略第 5 行并运行第 6 行,我不知道为什么!!!

#include <iostream>     // std::cin, std::cout

int main () {

char name[256], title[256];
std::cout << "Please, enter your name: ";
std::cin.getline (name,256,'$');                         //Line 3
std::cout << "Please, enter your favourite movie: ";
std::cin.getline (title,256);                            // Line 5
std::cout << name << "'s favourite movie is " << title;  // Line 6
return 0;
}

您可以使用以下解决方案来解决您的问题:

.....getline(title,256,'$')
//                      ^
//                      |
// this is where the delimiter goes in your function call

好像是这样工作的:

#include <iostream>     // std::cin, std::cout

int main () {

char name[256], title[256], endOfLine[2];
std::cout << "Please, enter your name: ";
std::cin.getline (name,256,'$');                         //Line 3
std::cin.getline(endOfLine, 1);
std::cout << "Please, enter your favourite movie: ";
std::cin.getline (title,256);                            // Line 5
std::cout << name << "'s favourite movie is " << title;  // Line 6
return 0;
}

让我猜你的输入是这样的:

> ./myProg
Please, enter your name: noob$
lease, enter your favourite movie: Top Gun
noob's favourite movie is 
>

在这里我们看到您输入了:noob$<return> 后跟 Top Gun<return>

问题是计算机看到的输入是:

noob$\nTop Gun\n

好的。那么代码中发生了什么。

std::cin.getline (name,256,'$');  // This reads upto the '$' and throws it away.

所以您的输入流现在看起来像:

\nTop Gun\n

注意流前面的“\n”。
现在你的下一行是:

std::cin.getline (title,256);  // This reads the next line.
                               // But the next line ends at the next new line
                               // which is the next character on the input stream.
                               // So title will be empty.

要修复它,您需要阅读该空行。
修复它的更好方法是不要求名称以 '$' 结尾。用户输入通常最好一次一行完成。当用户点击 return 时,缓冲区被刷新并且流实际上开始工作。该程序不会执行任何操作(除了等待),直到该缓冲区被刷新到流中(这通常在 return 上,但如果您只是键入很多内容,则可能会发生)。