在我的switch语句完全执行之前,我的while循环进入第二次迭代,我用c ++编码
My while loop goes into it's second iteration before my switch statement executes completely, I'm coding in c++
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
void ReadFile()
{
string fileName;
ifstream inFile;
cout << "Please enter the password for the external file: ";
getline(cin, fileName);
inFile.open(fileName);
}//End of ReadFile() function
int main()
{
vector<string> studentName, studentNumber, studentClass;
char option;
while (option != 'g' && option != 'G')
{
cout << "ttt" << "Student List Menunn";
cout << "A. Reading the Student List from a filen";
cout << "B. Adding Student's Informations into the Student Listn";
cout << "C. Displaying the content of the Student Listn";
cout << "D. Sorting and Displaying the content of the Student Listn";
cout << "E. Writing the Student List to a filen";
cout << "F. Searching for a Student's Information from the Student Listn";
cout << "G. Ending the programnn";
cout << "Please enter an option: ";
cin >> option;
cout << endl;
switch (option)
{
case 'A':
case 'a':
ReadFile();
break;
case 'B':
case 'b':
break;
case 'C':
case 'c':
break;
case 'D':
case 'd':
break;
case 'E':
case 'e':
break;
case 'F':
case 'f':
break;
case 'G':
case 'g':
cout << "Thank you for using the program!";
break;
default: cout << "Invalid option choicenn";
}
}
return 0;
}//End of main function
当我选择选项"A"时,switch 语句调用 ReadFile(( 函数,但是当它要求输入"密码"(文件名(时,会读取"学生列表菜单",我认为这意味着 do-while 循环在执行 ReadFile 函数时继续运行,因此它会读取输入直到换行符。我该怎么做才能让它先运行选项,然后继续执行 do-while 循环?
当您键入时
a
,然后按 Enter 键,在输入流中输入两个字符:a
和 'n'
。
当您使用
cin >> option;
在此类输入流上,首先读取'a'
。换行符仍在输入流中。
然后你调用ReadFile()
,它调用getline(cin, fileName)
。该调用将获得一个空字符串,因为换行符仍然存在于输入流中 - 它不会等待您输入文件名。之后,输入流中没有任何内容。此外,ReadFile()
返回。这就是您看到学生菜单的原因。
该问题的解决方法是在读取option
后忽略该行的其余部分。
cin >> option;
cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n');
替换getline(cin, fileName);
跟 cin>> fileName;
代码中的错误是由于行
getline(cin, fileName);
您必须使用
std::cin.getline(fileName,name length);
相关文章:
- 如何从给定字符串中删除第二次和第三次出现的$
- 为什么我的信号处理程序只执行一次?
- C++:std::ofstream 方法 open() 在第二次迭代时擦除打开的 ifstream 文件
- 为什么我的 2d 数组的第二行从 RAM 中获取随机值?
- 为什么程序运行时我的第二个循环不执行?
- arm_data在第二次运行我的程序时中止失败,然后
- 为什么我的第二个time_t变量没有正确显示
- 我的C 程序第二次运行时首先编写文件内容
- Visual C CLR设计器在项目的第二次运行和编辑设计中始终显示0x8000000A错误
- CIN.IGNORE删除第一个字符的第二次函数被调用
- Boyer-Moore多数投票算法的第二次通过要求
- qt :: qfiledialog第二次称为我的应用程序
- 在具有相同种子的同一程序中对srand()的第二次调用不会为连续的rand()生成相同的值
- QT 5.6:对QGraphicsScene::addItem()的第二次调用中出现分段冲突
- 在我的switch语句完全执行之前,我的while循环进入第二次迭代,我用c ++编码
- Windows启动时的第二次自动运行
- 我的 for 循环第一次正确输入,但第二次不正确,并显示第二个输入的输出。我不明白为什么会这样。
- c++ lambda在模板的第二次展开时没有捕获变量
- 引用数组的第二次元
- 主类无法从我的第二个类继承方法