gpt4 book ai didi

c++ - 使用 ifstream 读取文件

转载 作者:搜寻专家 更新时间:2023-10-31 01:23:19 27 4
gpt4 key购买 nike

我正在尝试从文件中读取:该文件是多行的,基本上我需要检查每个“单词”。词是任何非空间的东西。

示例输入文件为:

Sample file:

test 2d
word 3.5
input
{

test 13.5 12.3
another {
testing 145.4
}
}

所以我尝试了这样的事情:

ifstream inFile(fajl.c_str(), ifstream::in);

if(!inFile)
{
cout << "Cannot open " << fajl << endl;
exit(0);
}

string curr_str;
char curr_ch;
int curr_int;
float curr_float;

cout << "HERE\n";
inFile >> curr_str;

cout << "Read " << curr_str << endl;

问题是当它读取新行时它只是挂起。我阅读了测试 13.5 之前的所有内容但是一旦到达那条线,它就什么都不做。谁能告诉我我做错了什么?关于如何做到这一点有更好的建议吗???

我基本上需要浏览文件并在当时执行一个“单词”(非白色字符)。我

谢谢

最佳答案

您打开一个文件“inFile”但正在从“std::cin”中读取任何特定原因?

/*
* Open the file.
*/
std::ifstream inFile(fajl.c_str()); // use input file stream don't.
// Then you don't need explicitly specify
// that input flag in second parameter
if (!inFile) // Test for error.
{
std::cerr << "Error opening file:\n";
exit(1);
}

std::string word;
while(inFile >> word) // while reading a word succeeds. Note >> operator with string
{ // Will read 1 space separated word.
std::cout << "Word(" << word << ")\n";
}

关于c++ - 使用 ifstream 读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1619604/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com