2017-09-15 54 views
-2

所以,我一直有一个问题,我的程序试图读取文件,“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; 
} 
+0

'while'循环会读取* all *文件的内容。以下'for'循环将尝试从EOF之外读取。如果你在'for'循环条件中添加一个检查(例如'i > name'),那么你会发现它根本不会运行。 –

+0

我该如何回到文件的开头? – FreckledTerror97

+0

您是否尝试阅读您的C++书,它解释了如何使用'std :: ifstream'。 –

回答

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; 

} 
+0

唯一的问题,该文件不再组织,这是第一个文件流的点 – FreckledTerror97

+0

@ FreckledTerror97第一个循环完全在内存中运行。它不写回文件。事实上,它并不真正重新排序。它所做的只是记录找到的名字和姓氏。考虑另一种方式将文件读入'std :: vector',将'vector'的内容排序('std :: sort'可以帮助这里),然后打印出'vector'的内容。 – user4581301

+0

这是一个家庭作业问题,它不应该使用一个向量 – FreckledTerror97

相关问题