Unknown
Unknown

Reputation: 9

Count spaces for each line

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

Upvotes: 0

Views: 238

Answers (1)

Jack Ashton
Jack Ashton

Reputation: 85

Well, just change your for-loop:

n = 0; // After each line
for(int j=0; j<line.size(); j++)
{
    if (line[j] == ' ') n++;
}

Upvotes: 1

Related Questions