Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::cout not working inside a for-loop

Tags:

c++

for-loop

cout

I'm new to C++, and right now I'm learning from the book called Accelerated C++. I finished the third chapter (vectors), and I came to this exercise:

"Write a program to count how many times each distinct word appears in its input."

After some thinking, I started working on it. I wanted to test the program, but std::cout wasn't working. I put cout << "test"; on a few places in my code to see where's the problem, and the conclusion is that it doesn't work inside the first for-loop. Don't recommend me to use maps to solve the problem, because I'm working on vectors. The variables aren't in English, so I'll translate some for you to know what's going on:

recenica - the sentence; rijec - a word; vel_vektora - size of the vector; duz_recenice - length of the sentence; br_ponavljanja - number of times a word appears in the sentence;

#include <vector>
#include <iostream>
#include <string>

using std::string;      using std::vector;
using std::cin;         using std::cout;
using std::endl;



int main()
{
    string rijec;
    vector<string> recenica;

    while (cin >> rijec) recenica.push_back(rijec);
    cout << endl;

    typedef vector<string>::size_type vel_vektora;
    vel_vektora duz_recenice = recenica.size();
    cout << "test0, ";

    for (int i = 0; i < duz_recenice - 1; ++i)            
    {   
        cout << "test, !";
        int br_ponavljanja = 1;

        for (int j = i + 1; j < duz_recenice; ++j)
        {
                cout << "test2, ";
                if (recenica[i] == recenica[j])
                {
                                cout << "test3, ";
                                ++br_ponavljanja;
                                recenica.erase(recenica.begin() + j);
                }     
                cout << "test4, ";
        }        
        cout << recenica[i] << ": " << br_ponavljanja << endl;        
    }
    cout << "test5, ";                
    getchar();
    return 0;        
}

What's the problem with the std::cout?

like image 310
Bane Bojanić Avatar asked Mar 23 '26 10:03

Bane Bojanić


1 Answers

Add << flush to flush your output buffer (each place).

Or use << endl, which both adds newline and flushes.

There are problems with the code, especially for empty input, but that's what you're out to learn about, so I'll leave you to it! :-)

Cheers & hth.,

like image 70
Cheers and hth. - Alf Avatar answered Mar 25 '26 01:03

Cheers and hth. - Alf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!