使用ifstream读取文件

3
我正在尝试从文件中读取内容:
该文件包含多行文本,我需要逐个“单词”进行处理。单词指任何非空格字符。
示例输入文件如下:

示例文件:

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之前的所有内容,但是一旦到达那一行,程序就不再执行任何操作。 有人能告诉我我做错了什么吗? 有更好的建议吗?
本质上,我需要逐个“单词”(非空格字符)遍历文件。
谢谢。
2个回答

3
您打开一个名为“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";
}

我本来是想说的是 inFile >> 而不是程序本身中的问题。 - undefined

1

不确定这是否符合iostream库的“精神”,但你可以使用未格式化的输入来实现。类似于:

char tempCharacter;
std::string currentWord;
while (file.get(tempCharacter))
{
    if (tempCharacter == '\t' || tempCharacter == '\n' || tempCharacter == '\r' || tempCharacter == ' ')
    {
        std::cout << "Current Word: " << currentWord << std::endl;
        currentWord.clear();
        continue;
    }
    currentWord.push_back(tempCharacter);
}

这个行吗?


1
那样做是行不通的,因为istream::get函数不接受单个char*作为参数,并且在执行读取操作之前检查!file.eof()并不总是有效。此外,你正在将宽字符字面量与类型为char的窄对象进行比较(这些类型不兼容)。我会帮你编辑一下以修复这个问题。 - undefined
@0x499602D2:感谢你修复了那个问题 :) - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接