从fstream中读取单个字符?

时间:2012-02-07 13:12:54

标签: c++ file-io iostream fstream

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

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

  1. 从文本文件中读取单个字符。
  2. 根据该角色调用函数。
  3. 重复,直到我读完文件中的所有字符。
  4. 到目前为止我所拥有的......并不多:

    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;
    }
    

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

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

    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;
    }
    

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

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

5 个答案:

答案 0 :(得分: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;
  }
}

答案 1 :(得分: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
    }
}

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

答案 2 :(得分:1)

fstream::get

下次遇到类似问题时,请转到cplusplusreference或类似网站,找到您遇到问题的class并阅读每种方法的说明。通常,这解决了这个问题。谷歌搜索也有效。

答案 3 :(得分:0)

这已经得到了回答,但无论如何。 您可以使用comma operator创建一个循环,其行为类似于每个循环,遍历整个文件逐个读取每个字符,并在完成后停止。

char c;
while((file.get(c), file.eof()) == false){
    /*Your switch statement with c*/
}

<强>解释: for循环(file.get(c), file.eof())中表达式的第一部分 将起到如下作用。首先执行file.get(c),它读取一个字符并将结果存储在c中。然后,由于逗号运算符,将丢弃返回值并执行file.eof(),无论是否已到达文件的末尾,都会返回bool。然后比较该值。

旁注: ifstream::get()始终读取下一个字符。这意味着调用它两次会读取文件中的前两个字符。

答案 4 :(得分:-2)

while (textFile.good()) {
  char a;
  textFile.get(a);
   switch(a)
        {
        case 1:
            //dosomething
              break;
        case ' ':
            //dosomething etc etc
              break;
        case '\n':
    }
}
相关问题