0

Hi I'm writing a program in which the program reads lines from a text file and then it outputs the size of each line and also how many spaces are in every line. I'm having trouble with the second part with spaces, when it finds a space it just keeps that number and outputs it for every line below. So I would like to know how can I set the counter back to 0. This is my code:

if(myfile.is_open()) {
    while(!myfile.eof()) {

        i++;
        getline(myfile,line);
        strcpy(ch, line.c_str());
        r=r+line.length();

        for(int j=0; j<line.size(); j++) {
            if(line[j]==' ') {
                status = true;
                n++;
            } else {
                n = 0;
            }
        }

        std::cout << i << ". " << ch << " -- " << " (" << line.size() << ") " << " number of spaces: " << n << std::endl;
    }
}
npas
  • 113
  • 2
  • 7
  • 1
    Please read about [how to ask good questions](http://stackoverflow.com/help/how-to-ask), as well as [this question checklist](https://codeblog.jonskeet.uk/2012/11/24/stack-overflow-question-checklist/). And please try to create a [mcve] to show us. – Some programmer dude Dec 04 '18 at 16:55
  • 3
    And please read [Why is iostream::eof inside a loop condition considered wrong?](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) – Some programmer dude Dec 04 '18 at 16:56
  • 1
    You seem to reset `n` to zero whenever you encounter a non-space character. You must get the counter to work correctly *for one line* before you worry about many lines. – Beta Dec 04 '18 at 16:59

1 Answers1

1

Well, just change your for-loop:

n = 0; // After each line
for(int j=0; j<line.size(); j++)
{
    if (line[j] == ' ') n++;
}
  • Thank you for your answer, you were very close. I only had to put n before the for loop. Well thanks again :) – Unknown Dec 04 '18 at 17:34