It is necessary to count the number of words in each line for further action. The function works with a regular line, but when the buffer is transferred to it, which contains (or should contain a line from the file), the function does not work and returns 1. It looks like a primitive task, but I cannot find the error. Thong, please do not offer.

Code:

int CountWords(char str[]) { int counter = 0; char* c = strtok(str, " "); while (c) { c = strtok(NULL, " "); counter++; } return counter; } void DeleteMaxWords(const char path[]) {//здесь ищу строку с макисмальным количеством слов ifstream f(path); char buf[50]; int i = 0; int _strNum = 0; int _maxWords = 0; while ( !f.eof() ) { f.getline(buf, 50); if (CountWords(buf) > _maxWords) { cout << CountWords(buf) << endl; _maxWords = CountWords(buf); _strNum = i; } ++i; //cout << _maxWords << endl; } } 

    1 answer 1

    From the description of strtok :

    This function is destructive: str. In particular, a string literal cannot be used.

    Accordingly, spaces become '\ 0' and the second pass reads only one word. How to fix? Call once before if and write to a variable and then use the variable, and why call the algorithm 10 times in a row, when you can only 1 time. In addition, there is another error.

    Wrong:

     while ( !f.eof() ) { f.getline(buf, 50); ... } 

    Because f.eof () will be true only after trying to read when the end of the file has been reached.

     while (f.getline(buf, 50)) { int k = CountWords(buf); if (k > _maxWords) { cout << k << endl; _maxWords = k; _strNum = i; } ++i; //cout << _maxWords << endl; } 
    • I thank for the detailed answer, how interesting it turned out with the function call, that is, it turns out, in my version if (CountWords (buf)> _maxWords) my function rests on the space, but in yours - not. Honestly, to my shame, I did not really understand why. I realized that strtok, after finding the lexeme, puts a null character, and then something crazy doesn’t have to dock with the results. - Tovarisch 7:01 pm
    • The @Tovarisch function works fine for the first time, but replaces all spaces in the buf with a null character. And strtok () works until the end of the null character. Calling this function on this buffer again, strtok will see only one word - Drawn Raccoon
    • I understood! In the second function call, when I want to simply output the value, my string is already changed, contains null characters instead of spaces, thanks again, all the best! - Tovarisch