2015-05-06 150 views
-5

我從一個文本文件中讀取各行,並試圖打印出來就在命令提示符下各行,但文字只是閃爍真的很快和消失。C++打印文本在for循環中

我在readable.txt

cout << "These are the names of your accounts: " << endl; 
for (int b = 1; b <= i; b++) 
{ 
    fstream file("readable.txt"); 

    GotoLine(file, b); 

    string line; 
    file >> line; 

    cout << line << endl; 
} 
cin.ignore();      
break; 

任何幫助,將不勝感激設定的行數。

回答

0

錯誤: 在循環內打開fstream?那是自殺,你fstream的是永遠不變的你爲什麼要打開它每次迭代?

文本可能消失,因爲你的程序結束和經銷商的退出,你應該在休息前他等待或到達結束前

0

你不需要每次都重新打開文件並調用GotoLine(file, b);可以打開它,一旦外面的for循環,並通過std::getline(file, line)讀取字符串。

如果你想觀看的輸出中,只是在for循環插入system("pause")。如果你想在每行後暫停輸入,在的結束for循環插入getchar()(其內部)

0

斷裂是無稽之談(如果該片段是不是在一個循環或交換機。 我對消失的猜測文字是用IDE的干擾。嘗試在一個終端/主機。 正如在其他的答案,打開文件應該是外循環。

#include <iostream> 
#include <fstream> 

using namespace std; 

void GotoLine(fstream &f, int b) 
{ 
    char buf [999]; 
    while (b > 0) { f.getline (buf, 1000); b--; } 
} 

int main() 
{ 
    int i = 5; 
    cout << "These are the names of your accounts: " << endl; 
    for (int b = 1; b <= i; b++) 
    { 
     fstream fl("readable.txt"); 
     GotoLine(fl, b); 

     string line; 
     fl >> line; 

     cout << line << endl; 
    } 
} 
0

首先避免打開一個文件內的循環。您在這裏做了很多亂七八糟的。 試試這個代碼

std::ifstream file("readable.txt"); 
file.open("readable.txt"); 

if(file.fail()) 
{ 
    std::cout << "File cannot be opened" << std::endl; 
    return EXIT_FAILURE; 
} 

std::string line; 

while std::getline(file, line) // This line allows to read a data line by line 
{ 
    std::cout << line << std::endl; 
} 

file.close(); 

system("PAUSE"); // This line allows the console to wait 
return EXIT_SUCCESS;