C++ 为什么我的循环不能正常工作?
我有下面的代码,允许用户修改文件。我的问题是,当我运行它时,一旦它工作了。但是假设我想再次打开txt文件,但它没有打开C++ 为什么我的循环不能正常工作?,c++,C++,我有下面的代码,允许用户修改文件。我的问题是,当我运行它时,一旦它工作了。但是假设我想再次打开txt文件,但它没有打开 string line, line2; string data, moduleID, input; int Choice; ifstream samsFile("SAMS.txt"); fstream registeredModule("210CTStudentModule.txt"); if(! samsFile){ cout << "Error Ope
string line, line2;
string data, moduleID, input;
int Choice;
ifstream samsFile("SAMS.txt");
fstream registeredModule("210CTStudentModule.txt");
if(! samsFile){
cout << "Error Opening File" << endl;
return 0;
}
do{
cout<<"HELLO AND WELCOME!!!"<<endl;
cout<<"what do you want to do?"<<endl;
cout<<"1: Check Registered Students"<<endl;
cout<<"2: Register Student To Module"<<endl;
cout<<"3: Open Registered Module File"<<endl;
cout<<"4: Logout"<< endl;
cin>>Choice;
if(Choice==1){
while(getline(samsFile,line)){
cout<<line<<endl;
}
}else if(Choice==2){
vector<string>example;
while(getline(samsFile,data)){
example.push_back(data);
}
cout<<"What Module Do You Want To Add?: "<<endl;
cin.ignore();
cin>>moduleID;
vector<string>moduleCode;
for(unsigned int j=0;j<example.size();j++){
moduleCode.push_back(moduleID);
}
for(unsigned int k=0;k<moduleCode.size();k++){
registeredModule<<moduleCode[k]<<" "<<example[k]<<"\n";
}
}else if(Choice==3){
while(getline(registeredModule,line2)){
cout<<line2<<endl;
}
}
}while(Choice!=4);
cout << "Goodbye" << endl;
return 0;
字符串行,第2行;
字符串数据,moduleID,输入;
智力选择;
ifstream samsFile(“SAMS.txt”);
fstream注册模块(“210CTStudentModule.txt”);
如果(!samsFile){
cout如果每次都要通过循环打开文件,请将流的初始化放在循环内。离开作用域时文件将关闭,进入时文件将打开
如果您不介意一直打开它,问题是您在循环的第二次中处于文件的末尾,那么每次通过循环时,您都可以使用seekg将自己重新定位到文件的开头。我编辑了您的一段代码。在循环的中声明“samsFile”(正如Basya Perlman所说)
do{
ifstream samsFile(“SAMS.txt”);
你能在哪里再次打开?请提供一个。你在这里显示的代码只打开一次文件,哪个文件-这里有两个文件正在打开我猜你的问题是,在循环的第二次中,你位于文件的末尾,因此无法读取它。对吗?是的,我看到我在做while循环,现在它工作。谢谢。我学习C++一段时间,但暂时没有练习。谢谢输入。
do{
ifstream samsFile("SAMS.txt");
cout<<"HELLO AND WELCOME!!!"<<endl;
cout<<"what do you want to do?"<<endl;
cout<<"1: Check Registered Students"<<endl;
cout<<"2: Register Student To Module"<<endl;
cout<<"3: Open Registered Module File"<<endl;
cout<<"4: Logout"<< endl;
cin>>Choice;
if(Choice == 1){
while(getline(samsFile,line)){
cout<<line<<endl;
}
}
}while(Choice!=4);
cout << "Goodbye" << endl;