从fstream中读取单个字符?

Jcr*_*ack 8 c++ file-io fstream iostream

我正试图从stdio转移到iostream,这证明非常困难.我已经掌握了加载文件并关闭文件的基础知识,但我真的不知道什么是流甚至是什么,或者它们是如何工作的.

在stdio中,与此相比,一切都相对容易和直接.我需要做的是

  1. 从文本文件中读取单个字符.
  2. 根据该角色调用函数.
  3. 重复,直到我读完文件中的所有字符.

到目前为止我所拥有的......并不多:

int main()
{
    std::ifstream("sometextfile.txt", std::ios::in);
    // this is SUPPOSED to be the while loop for reading.  I got here and realized I have 
    //no idea how to even read a file
    while()
    {
    }
return 0;
}
Run Code Online (Sandbox Code Playgroud)

我需要知道的是如何获得单个字符以及该字符实际存储的方式(它是一个字符串吗?一个int?一个char?我可以自己决定如何存储它吗?)

一旦我知道我认为我可以处理其余的事情.我将角色存储在适当的容器中,然后使用开关根据角色的实际情况做事.它看起来像这样.

int main()
{
    std::ifstream textFile("sometextfile.txt", std::ios::in);

    while(..able to read?)
    {
        char/int/string readItem;
        //this is where the fstream would get the character and I assume stick it into readItem?
        switch(readItem)
        {
        case 1:
            //dosomething
              break;
        case ' ':
            //dosomething etc etc
              break;
        case '\n':
        }
    }
return 0;
}
Run Code Online (Sandbox Code Playgroud)

请注意,我需要能够检查空格和新行,希望它是可能的.如果不是一个通用容器,我可以将数字存储在一个字符串中的int和chars中,这也很方便.如果不是,我可以解决它.

感谢任何能够向我解释流如何工作以及它们可以实现的功能的人.

Xeo*_*Xeo 8

streambuf_iterator如果你想使用任何算法,你也可以抽象出用s 获取单个字符的整个想法:

#include <iterator>
#include <fstream>

int main(){
  typedef std::istreambuf_iterator<char> buf_iter;
  std::fstream file("name");
  for(buf_iter i(file), e; i != e; ++i){
    char c = *i;
  }
}
Run Code Online (Sandbox Code Playgroud)


jro*_*rok 7

您也可以使用标准for_each算法:

#include <iterator>
#include <algorithm>
#include <fstream>

void handleChar(const char& c)
{
    switch (c) {
        case 'a': // do something
            break;
        case 'b': // do something else
            break;
        // etc.
    }
}

int main()
{
    std::ifstream file("file.txt");
    if (file)
        std::for_each(std::istream_iterator<char>(file),
                      std::istream_iterator<char>(),
                      handleChar);
    else {
        // couldn't open the file
    }
}
Run Code Online (Sandbox Code Playgroud)

istream_iterator跳过空白字符.如果这些在您的文件中有意义,请istreambuf_iterator改为使用.