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

示例输入文件将是:

  

示例文件:

     

测试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之前读了一切 但是一旦达到那条线,就什么也做不了。 谁能告诉我我做错了什么? 关于如何做到这一点的任何更好的建议???

我基本上需要浏览文件并转到“word”字样。 (非白色炭)当时。 我

由于

有帮助吗?

解决方案

你打开一个文件'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";
}

其他提示

不确定“在精神上”是怎样的这是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);
}

这有用吗?

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top