C++ 我的while循环进入其中';在switch语句完全执行之前的第二次迭代,I';m用c+编码+; #包括 #包括 #包括 #包括 #包括 使用名称空间std; void ReadFile() { 字符串文件名; 河流充填; 当你打字时不能
C++ 我的while循环进入其中';在switch语句完全执行之前的第二次迭代,I';m用c+编码+; #包括 #包括 #包括 #包括 #包括 使用名称空间std; void ReadFile() { 字符串文件名; 河流充填; 当你打字时不能,c++,switch-statement,do-while,C++,Switch Statement,Do While,#include <iostream> #include <iomanip> #include <fstream> #include <string> #include <vector> using namespace std; void ReadFile() { string fileName; ifstream inFile; cout << "Please enter the passw
#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 << "\t\t\t" << "Student List Menu\n\n";
cout << "A. Reading the Student List from a file\n";
cout << "B. Adding Student's Informations into the Student List\n";
cout << "C. Displaying the content of the Student List\n";
cout << "D. Sorting and Displaying the content of the Student List\n";
cout << "E. Writing the Student List to a file\n";
cout << "F. Searching for a Student's Information from the Student List\n";
cout << "G. Ending the program\n\n";
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 choice\n\n";
}
}
return 0;
}//End of main function
在终端中,按Enter键,在输入流中输入两个字符:a
和'\n'
当你使用
a
在这样的输入流中,首先读取'a'
。换行符仍在输入流中
然后调用ReadFile()
,它调用getline(cin,fileName)
。该调用会得到一个空字符串,因为换行符仍然存在于输入流中——它不会等待您输入文件名。此后,输入流中没有任何内容。另外,ReadFile()
返回。这就是您看到学员菜单的原因
解决此问题的方法是在读取选项
后忽略行的其余部分
cin >> option;
cin>>选项;
cin.ignore(std::numeric_limits::max(),'\n');
代码中的错误是由行引起的
cin >> option;
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
你必须使用
getline(cin, fileName);
替换getline(cin,文件名);
与
cin>>fileName;
问题出在函数getline(cin,fileName)中;这是不可行的,可能是重复的哦,没错,我完全忘记了那讨厌的额外新行字符,谢谢!如果可以的话,我会投你一票,但我刚刚加入,谢谢!不管怎样,skipws
默认是打开的……这里的解决方案是在调用之前消耗选项之后的剩余行nggetline
,例如-使用ignore
。
std::cin.getline(fileName,name length);