所以,我一直遇到一个问题,我的程序试图读取一个文件,“LineUp.txt”,我组织文件的名称按字母顺序排列,但它不会读取多个名称,它只是一遍又一遍地读取名字。我正在使用for循环,而不是while循环,这在其他问题中我没有见过。我很感激帮助!这是代码:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main (){
ifstream myFile;
string name, front, back;
int numOfStudents, i;
myFile.open("LineUp.txt");
if(!myFile)
cout << "File not found";
cout << "Please enter the number of students: ";
cin >> numOfStudents;
myFile >> name;
front = name;
back = name;
while(myFile >> name){
if(name < front)
front = name;
if(name > back)
back = name;
}
for(i = 0; i < numOfStudents; i++){
myFile >> name;
cout << name << endl;
}
return 0;
}
答案 0 :(得分:0)
while循环会耗尽您的输入流。
如果您想再次从文件中读取,则必须创建新的输入流。
myFile.open("LineUp.txt");
if(!myFile)
cout << "File not found";
cout << "Please enter the number of students: ";
cin >> numOfStudents;
myFile >> name;
front = name;
back = name;
while(myFile >> name){
if(name < front)
front = name;
if(name > back)
back = name;
}
ifstream myFile2("LineUp.txt"); //Create a new stream
for(i = 0; i < numOfStudents; i++){
myFile2 >> name;
cout << name << endl;
}