C++跳过CIN语句。进入无限循环
出于某种原因,它第一次进入cin语句,但在代码中每隔一次就跳过一次。在运行了几次之后,我意识到由于某种原因,它进入了默认情况,甚至不需要用户输入。为什么? 这是密码。这是一个带有巨大开关语句的菜单。switch语句中的函数在这里不相关,因为它只是整个循环C++跳过CIN语句。进入无限循环,c++,loops,cin,infinite,C++,Loops,Cin,Infinite,出于某种原因,它第一次进入cin语句,但在代码中每隔一次就跳过一次。在运行了几次之后,我意识到由于某种原因,它进入了默认情况,甚至不需要用户输入。为什么? 这是密码。这是一个带有巨大开关语句的菜单。switch语句中的函数在这里不相关,因为它只是整个循环 int main() { Document* myDocs = new Document[10]; int docCount = 0; bool menu = true; int userInput = 0;
int main()
{
Document* myDocs = new Document[10];
int docCount = 0;
bool menu = true;
int userInput = 0;
while ( menu == true )
{
//int userInput = 0;
userInput = 0;
cout << "----------------MENU----------------" << endl << endl;
cout << " --------(1) LOAD DOCUMENT (1)--------- " << endl << endl;
cout << "--------(2) OUTPUT DOCUMENT (2)--------" << endl << endl;
cout << " --------(3) ANALYZE DOCUMENT (3)-------- " << endl << endl;
cout << " ------(4) COMPARE TWO DOCUMENTS (4)------ " << endl << endl;
cout << " ----------(5) ENCRYPT (5)---------- " << endl << endl;
cout << "-----------(6) DECRYPT (6)----------" << endl << endl;
cout << "-------------(7) EXIT (7)--------------" << endl << endl;
cin >> userInput;
string docName;
string outputLoc;
switch (userInput)
{
case 1:
// Function
break;
case 2:
// Function
break;
case 3-8:
// Function
break;
default:
break;
}
基本上,我首先输入第一个userinput。假设我输入1。然后进入案例1。但当它退出案例1后,它进入一个无限循环,继续显示菜单。它不应该在cin声明上停止吗?这就是我不明白的
编辑::
案例1是我最担心的一个,因为我一个接一个地尝试,案例1不起作用。
这是案例1的完整代码:
case 1: // Load Document
{
string inputLoc;
cout << "Please input the document name:" << endl;
cin >> docName;
myDocs[docCount].setName(docName);
myDocs[docCount].id = docCount;
cout << "Input Location: " << endl;
cin >> inputLoc;
myDocs[docCount].loadDocument(inputLoc);
docCount++;
break;
}
我开始猜测我的loadDocument函数有问题。
以下是代码:
void Document::loadDocument(string name)
{
ifstream myFile(name);
int numOflines = 0;
string theLine;
char words;
while (myFile.get(words))
{
switch (words)
{
case '.':
numOflines++;
break;
case '?':
numOflines++;
break;
case '!':
numOflines++;
break;
}
}
lineCount = numOflines;
setLineCt(numOflines);
arr = new Line[lineCount];
myFile.close();
char theChar;
ifstream myFile2(name);
int key = 0;
if (myFile2.is_open())
{
for ( id = 0; id < lineCount; id++ )
{
while (myFile2>> noskipws>>theChar && theChar != '.' && theChar != '!' && theChar != '?') // Changed from || to &&
{
//myFile2>> noskipws >> theChar;
theLine[key] = theChar;
key++;
}
myFile2>>theChar;
arr[id].setStr(theLine);
}
}
}
基本上,我试图加载文档并存储其中的字数和行数。有什么问题吗?您的程序中是否真的有案例3-8:的可能重复?您可以发布main的其余部分吗?问题不清楚我尝试了您的代码,一切都正常。尝试设置一些断点并知道问题的确切位置,或者把你的空洞代码和你插入的内容放在一起。在800行中,你可能需要考虑一些重构。