我试图为Linux制作一个命令行邮件应用程序(虽然我是在Xcode上开发的,因为虚拟机对我的电脑来说很耗电)。我在主菜单中有两个选项(用户输入数字选择)。我在每次输入后都会使用这个选项,无论是简单的can还是get line(can, stringName)。
void clearCin() {
cin.clear();
cin.ignore(INT_MAX, '\n');
}
这就是为什么我很困惑,我的输入会出现各种奇怪的行为。这是我的代码和一个输出示例(最后的函数只是一个for循环,做cost << endl;)。
代码
bool stdEmail() {
string to, cc, bcc, subject, message;
cout << "When entering email addresses, seperate multiple email addresses with a space";
endl(2);
cout << "To: ";
getline(cin, to);
clearCin();
cout << "cc: ";
getline(cin, cc);
clearCin();
cout << "bcc: ";
getline(cin, bcc);
clearCin();
endl(1);
cout << "Subject: ";
getline(cin, subject);
clearCin();
endl(1);
cout << "Now enter your message, when you're finished, type a period on a new line";
endl(2);
ofstream file;
file.open("newMessage.txt", fstream::trunc);
bool repeat = true;
while (repeat) {
getline(cin, message);
clearCin();
if (message == ".") {
repeat = false;
} else {
file << message << endl;
}
}
file.close();
return true;
}
产量
--------------------------------------------------
Welcome to mark's Multi-Mail program
Main menu:
--------------------------------------------------
1. Send personalized emails to multiple recipients
2. Send a standard email
3. Exit the program
--------------------------------------------------
2
When entering email addresses, seperate multiple email addresses with a space
To: [email protected] [email protected]
cc: [email protected]
bcc:
Subject: Thanks for your help!
Now enter your message, when you're finished, type a period on a new line
Here is a sample message
.
Now I am trying to get it out of taking the message which should have happened when I typed a .
.
Program ending Have a Nice Day
Program ended with exit code: 0
下面是newMessage.txt中显示的内容。
以下是一个示例信息
cin.ignore(INT_MAX, '\n');
丢弃换行,getline在读取换行时完成,所以你必须在输入信息后按两次回车键才能让getline读取信息,你必须在输入'.'后按两次回车键才能结束循环。