繁体   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