如何使用for循环使文件进入下一行



所以,我一直在遇到一个问题,我的程序正在尝试读取文件" lineup.txt",我组织了文件以具有字母的名称,但它赢了't读多个名称,它只是一遍又一遍地读取名字。我正在使用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循环会耗尽您的输入流。

如果要再次从文件中读取,则必须创建一个新的输入流。

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;
}

最新更新