C ++从文本文件读取直到给定字符

用户名

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

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

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

加布

我建议在进行实际实施之前先阅读文档

我建议使用第一个重载(也存储字符)来检查是否要迭代正确的整数。

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章