为什么我的输入在这个C++程序中如此混乱

Why is my input so messed up in this C++ program?

本文关键字:程序 混乱 C++ 我的 输入 为什么      更新时间:2024-03-29

我正在尝试制作一个适用于Linux的命令行邮件应用程序(尽管我是在Xcode上开发的,因为虚拟机会占用我的计算机大量的电源(。我在主菜单中有两个选项(用户输入一个数字进行选择(。我在每次输入后都使用这个,无论是简单的can还是get行(can,stringName(:

void clearCin() {
cin.clear();
cin.ignore(INT_MAX, 'n');
}

这就是为什么我感到困惑,因为我的输入中出现了各种奇怪的行为。这是我的代码和一个示例输出(结束函数只是一个for循环,它的成本为<<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: one@example.com two@example.com
cc: three@example.com
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在读取换行符时完成,因此您必须在键入消息后按enter两次才能让getline读取它,并且您必须在输入"后按enter二次结束你的循环。