简体   繁体   中英

Strange problem with std::cout

I have 2 loops:

//Loop 1
for ( vector<string>::iterator iter = vecv.begin() ; iter != vecv.end()  ; iter++)
    {
        cout << "-----IN LOOP----" <<  *iter;
    }

//Loop 2
for ( vector<string>::iterator iter = vecv.begin() ; iter != vecv.end()  ; iter++)
    {
        cout << "-----IN LOOP----" <<  *iter << endl ;
    }

Now vecv is a string vector and contains 2 strings:

65 and A000 respectively.

Now the loop 1 Does not print anything, in fact the loop seems to not run at all.

However on adding the endl as you see in Loop 2, it gives this output:

-----IN LOOP----65
-----IN LOOP----$A000

What is happening exactly?

Mind you i am facing this problem only in Visual Studio 2010 and not Dev-C++!!

std::endl also flushes the buffer. If you want to flush without linebreak, use std::flush .

How do you know it doesn't print anything without endl ? By observing running program? If so, the problem is that cout provides buffered output: it actually prints somehting on the screen (or in the file) only when its buffer is full.

endl on other hands flushes the buffer.

If you want unbuffered output you can use cerr , but it would lead to some differences (like, now if you want to redirect output to file you should do 2> instead of > etc.)

If you want buffered output but don't want to have newlines, print flush into cout .

I think the cout.clear() just destroy the cout buffer. Since it has not been flushed therefore it's lost.

EDIT 1: Code providing :

#include <iostream>
#include <vector>

using namespace std;

int main(void) {

  vector<string> vecv;

  vecv.push_back("abc");
  vecv.push_back("def");

  //Loop 1
  for ( vector<string>::iterator iter = vecv.begin() ; iter != vecv.end()  ; iter++)
  {
    cout << "-----IN LOOP 1----" <<  *iter;
  }

  //Loop 2
  for ( vector<string>::iterator iter = vecv.begin() ; iter != vecv.end()  ; iter++)
  {
    cout << "-----IN LOOP 2----" <<  *iter << endl ;
  }
}

outputs :

./a.out
-----IN LOOP 1----abc-----IN LOOP 1----def-----IN LOOP 2----abc
-----IN LOOP 2----def

You are not showing the full program, but I suspect that it ends with a system("pause"); , as is often seen in tutorials for MSVC. MSVC runtime does not flush the output buffer when calling system() (it isn't required to), thus all output to std::cout remains buffered if no std::flush , std::endl , or input from std::cin were performed.

Try running your program in a console window (Start->Run->cmd.exe). The output should appear when the program terminates, even without endl .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM