0

I have a textfile in this form:

1 1
2 2
3 3
#
4 3
5 1

Now I want to read this textfile and count two variables num1 andnum2. num1 counts the number of all character´s until #and num2 counts the number of all character´s after #.

My code so far:

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

I have no idea how to write the code for my problem.

user3653164
  • 979
  • 1
  • 8
  • 24

2 Answers2

0

I recommend reading the documentation briefly before proceeding to an actual implementation.

I suggest using the first overload (storing the character as well) to check if you're iterating the right integer.

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;
    }
}
Gabe
  • 961
  • 1
  • 10
  • 23
-1

why not simply read character by character as below

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++
    }
}
Codeek
  • 1,624
  • 1
  • 11
  • 20
  • [Why is iostream::eof inside a loop condition (i.e. `while (!stream.eof())`) considered wrong?](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons) – user4581301 Feb 03 '22 at 01:57