2

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

示例输入文件将是:

示例文件:

测试 2d
字 3.5
输入
{

测试 13.5 12.3
另一个 {
测试 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 之前阅读了所有内容,但是一旦到达该行,它就什么也不做。谁能告诉我我做错了什么?关于如何做到这一点的任何更好的建议???

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

谢谢

4

2 回答 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";
}
于 2009-10-25T00:43:00.017 回答
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);
}

那样有用吗?

于 2009-10-25T05:00:14.493 回答