所以,我一直有一个问题,我的程序试图读取文件,“LineUp.txt”,并且我组织文件到名称按字母顺序排列,但不会读取多个名称,它只是反复读取第一个名称。我正在使用for循环,而不是一个while循环,在其他问题中我从未见过。我感谢帮助!以下是代码:如何让一个文件移动到下一行使用for循环
#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;
}
'while'循环会读取* all *文件的内容。以下'for'循环将尝试从EOF之外读取。如果你在'for'循环条件中添加一个检查(例如'i> name'),那么你会发现它根本不会运行。 –
我该如何回到文件的开头? – FreckledTerror97
您是否尝试阅读您的C++书,它解释了如何使用'std :: ifstream'。 –