Cin内部切换语句,使我的程序陷入困境



在我的程序中,应该可以选择要求用户输入,然后将输入字符串保存到文件中。我的问题是,当我把cin放在Switch中的任何一种形式时,程序都会无限期地循环,就在我输入完新文本后按enter键之后。是什么原因导致了问题?


#include <iostream>
#include <fstream>
#include <iterator>
#include <string.h>
#include <time.h>
#include <stdlib.h>
#include <algorithm>
#include <chrono>
#include <random>
#include <vector>
using namespace std;
void changePlainText()
{
ofstream nFile("plaintext.txt");
string newText;
cout << "Enter new plain text" << endl;
getline(cin, newText);
nFile << newText;
nFile.close();
}
int main()
{
int uInput = 0;
do
{
printf("2.Change content of the plain text file: n");
cin >> uInput;
switch (uInput)
{
case 1:
break;
case 2:
changePlainText();
break;
}
} while (uInput != 5);
cout << "Closing program" << endl;
system("pause");
}

当我在控制台中键入一些内容并按下回车键后,程序进入了一个永无止境的圆圈。即使我只写简单的cin>gt;i、 在开关情况下。

看看这个问题。我调试了你的代码,并体验到了这种行为。公认的答案很好地解释了正在发生的事情,也提供了一个解决方案。

我尝试了助推,我改变了

cin >> uInput;

string inputString; // so you know what inputString is

getline(cin, inputString);
uInput = boost::lexical_cast<int>(line);

现在运行良好。

最新更新