【问题标题】:C++ read from textfile until given characterC++ 从文本文件读取直到给定字符
【发布时间】:2015-03-08 19:14:35
【问题描述】:

我有一个这种形式的文本文件:

1 1
2 2
3 3
#
4 3
5 1

现在我想读取这个文本文件并计算两个变量num1num2num1 计算# 之前的所有字符数,num2 计算# 之后的所有字符数。

到目前为止我的代码:

Graph::Graph(string s) // s is the filename
{
    ifstream tgf(s);
    string line;
    // num1 and num2 are two private member (type int) of class Graph 
    num1 = 0; 
    num2 = 0;
    if(tgf.is_open())
    {
        while(getline(tgf, line, '#')) // this should read tgf until '#'
        {
            num1++;
        }
    } else
    {
        cout << "Can´t open textfile!" << endl;
    }
}

我不知道如何为我的问题编写代码。

【问题讨论】:

    标签: c++ string fstream getline stringstream


    【解决方案1】:

    我建议在进行实际实施之前简要阅读documentation

    我建议使用first overload(也存储字符)来检查您是否在迭代正确的整数。

    Graph::Graph(string s) // s is the filename
    {
        ifstream tgf(s);
        string line;
        // num1 and num2 are two private member (type int) of class Graph 
        num1 = 0; 
        num2 = 0;
        bool found_del = false;
        if(tgf.is_open())
        {
            while(getline(tgf, line)) // stores # as well
            {
                if(line == "#") found_del = true;
                else{
                  if(found_del) num1++; else num2++;
                } 
            }
        } else
        {
            cout << "Can´t open textfile!" << endl;
        }
    }
    

    【讨论】:

      【解决方案2】:

      为什么不简单地逐字阅读如下

      int startNewCount = 0;
      char my_character
      while (!tgf.eof() ) 
      {
          tgf.get(my_character);
          if (my_character != '#')
          {
              startNewCount=1;
          }
          if (my_character != ' ' && startNewCount==0)
          {
              num1++
          }
          else if(my_character != ' ' && startNewCount==1)
          {
              num2++
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-02-08
        • 1970-01-01
        • 1970-01-01
        • 2015-08-30
        相关资源
        最近更新 更多