簡體   English   中英

打開文本文件后為什么不打印我的cout語句?

[英]Why won't my cout statements print after opening a textfile?

我正在嘗試編寫一個程序,我在其中讀取文本文件,然后在文本文件中取出每一行並將它們存儲在字符串向量中。 我想我能夠打開文本文件,但是我注意到在打開文本文件后,該點之后的任何內容都沒有執行。 例如,我在main函數末尾有一個cout語句,當我輸入不存在的文件名時輸出。 但是,如果我輸入文件名確實存在,我從最后一個cout語句得不到輸出。 有誰知道這是為什么? 謝謝!

int main() { vector<string>line; string fileName = "test.txt"; ifstream myFile(fileName.c_str()); int i = 0; int count = 0; vector<string>lines; cout << "test" << endl; if (myFile.is_open()) { cout << "test2" << endl; while (!myFile.eof()) { getline(myFile, lines[i],'\n'); i++; } myFile.close(); } if (!myFile.is_open()) { cout<< "File not open"<< endl; } myFile.close(); cout << "Test3" <<endl; return 0; }

試試這個

string fileName = "test.txt";
ifstream myFile(fileName); // .c_str() not needed - ifstream can take an actual string
vector<string> lines;

string line; // temporary variable for std::getline
while (getline(myFile, line)) {
   lines.push_back(line); // use push_back to add new elements to the vector
}

正如評論中指出的那樣,你的程序似乎過早“結束”的最可能原因是它崩潰了。 std::getline將引用string作為其第二個參數。 在你的代碼中,你的向量是空的; 因此任何i lines[i]都返回對無效內存的引用。 getline嘗試訪問該內存時,程序崩潰。

如果您想要在嘗試訪問vector的越界索引時拋出異常,請使用lines.at(i)而不是lines[i]

你需要使用push_back()因為你的初始向量是空的,你不能在空向量上使用索引。 如果這樣做,將導致未定義的行為。

std::ifstream input( "filename.ext" );
std::vector<std::string> lines;
for( std::string line; getline( input, line ); )
{
    lines.push_back(line); 
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM