Solved

How does iostream cout really work?

Posted on 2004-04-08
16
1,664 Views
Last Modified: 2013-12-14
I'm puzzled by the following code. using printf() works fine, but for some reason, setting X_SIZE and Y_SIZE to 60 (and some other values) causes the program to output nothing using iostream's cout. With other values, cout works as expected. I tried cout.flush(), but no difference. I'm using the Visual C++ 7.0 command line compiler. Is there something about C++ streams that I'm missing here? Thank you very much and any advice greatly appreciated!


#include <assert.h>
#include <iostream>
#include <stdio.h>


const int X_SIZE = 60;
const int Y_SIZE = 60;

char graphics[X_SIZE / 8][Y_SIZE];
void printGraphics();

inline void setBit (const int x, const int y) {
      assert ((x>=0) && (x < X_SIZE));
      assert ((y>=0) && (y < Y_SIZE));
      graphics[x/8][y] |= (0x80 >> (x%8));
}

int main() {
      int loc;
      for (loc = 0; loc < X_SIZE; loc++) {
            setBit(loc, loc);
      }
      
      printGraphics();
      return 0;
}

void printGraphics() {
      int x, y, bit;
      
      for (y=0; y<Y_SIZE; y++) {
            for (x=0; x<X_SIZE/8; x++) {
                  for (bit=0x80; bit > 0; bit >>= 1) {
                        assert((x>=0) && (x < (X_SIZE / 8)));
                        assert((y>=0) && (y < Y_SIZE));
                        
                        if (((graphics[x][y] & bit) != 0)) {
                              //std::cout << "x";
                              printf("x");
                        } else {
                              //std::cout << ".";
                              printf(".");
                        }
                  }
                  
            }
            //std::cout << "\n";
            printf("\n");
      }
}
0
Comment
Question by:eching21
  • 6
  • 5
  • 2
  • +3
16 Comments
 

Expert Comment

by:Tarnge
Comment Utility
I found Icouldn't use cout (it gave me an 'undefined' error of some kind) unless I put namespaces in the code: -

#include <assert.h>
#include <iostream>
#include <stdio.h>

using namespace std;

const int X_SIZE = 60;
const int Y_SIZE = 60;

I think namespaces are religious to C++ to give standard libraries (ie <iostream>) scope.
0
 

Expert Comment

by:Tarnge
Comment Utility
I should have said this aswell: -

the namespace known as 'std' is apparently reserved by the compiler (short for standard I think) because it allows functions like cout (or something...) you can of course use your own in your programs, but should always start with this one.
0
 

Expert Comment

by:Tarnge
Comment Utility
I just tried your code (MS VC++ 5.0), opened a new Win32 Console Application, opened a new text file, pasted your code, saved the text file as Text1.cpp, and compiled and ran....it worked. Maybe your compiler options are different. (This was the output - and sorry about the multiple posts!)

x................................................................................
.x...............................................................................
..x..............................................................................
...x.............................................................................
....x............................................................................
.....x...........................................................................
......x..........................................................................
.......x.........................................................................
........x........................................................................
.........x.......................................................................
..........x......................................................................
0
 
LVL 16

Expert Comment

by:warturtle
Comment Utility
Hi,

Yes, use the "using namespace std;" in your program and it should work.

Regards,

Warturtle
0
 

Author Comment

by:eching21
Comment Utility
Hi everybody, thanks so much for the input!

Correct me if i'm wrong, but the "using namespace std;" is really just to get c++ to "use" (for lack of a better word) the entire std namespace, so you don't have to do things like std::cout << "blah", but can just do cout << "blah" because the c++ already knows that the std namespace (which houses the iostream functions among others), is being used in the program, and thus, all library functions default to the std namespace if not already defined.

However, if you notice in the code (the bits above the printf() calls that are commented out), i actually used std::cout. Does that give you a compile error as well? Or did you mean just using plain cout << "" without using the standard namespace?

I understand what you mean about the namespace problem, but the queer thing i'm facing is that the program does not print anything ONLY for X_SIZE = Y_SIZE = 60. And this only happens when I use cout (std::cout, or cout with "using namespace std"). For all other values (among those i tried at least), the program works fine with both printf and cout.

Hence, i'm wondering if the culprit is really with c++ streams (output stream in particular), because after all, plain old printf works without a problem for *all* values of X_SIZE and Y_SIZE.

Once again, thanks for any input!!
Eugene.
0
 

Author Comment

by:eching21
Comment Utility
Oh btw Tarnge, the code that I put up is using printf(), which will definitely work. The problem bits are the lines above the printf function calls, (i.e. the std::cout calls), which have been commented out.. :p

Sorry I didn't make that clear. My apologies.

Thanks once again!
Eugene.
0
 
LVL 10

Expert Comment

by:Kavar
Comment Utility
you could always macro cout to std::cout ...
0
 

Expert Comment

by:Tarnge
Comment Utility
Ok, I tried your code again. I removed the printf lines (to print the 'x' and the '.'), and took the comment marks away from the cout lines. As you said, you can either specify the std namespace at the beginning, or each time you call 'cout'. The program still works. In relation to your point about that the X_SIZE and Y_SIZE only work when they're 60, has to do with the assert functions. I'm using MS Visual C++5.0, and the DOS screen that comes up to run the program gives this error message: -

Assertion failed: (y>=0) && (y < Y_SIZE), file Text1.cpp, line 16.

Is this what you're getting or did your program not compile/run at all?

0
Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

 

Author Comment

by:eching21
Comment Utility
Hi Tarnge,

No, I mean the program does *not* work when X_SIZE = Y_SIZE = 60.

The program does compile, and there's no assertion failure. However, it simply doesn't print anything when X_SIZE = Y_SIZE = 60 *using* cout.

With all other values of X_SIZE and Y_SIZE, where X_SIZE <= Y_SIZE (it's a requirement else the assertion will fail), the program works.

Also, may I know what values of X_SIZE and Y_SIZE did you put in when you got the assertion failure?

Thanks!!
Eugene.
0
 

Expert Comment

by:Tarnge
Comment Utility
er......I've compiled again, and when SIZE_X and SIZE_Y are both 60, mine does compile. The only thing I can think of is that you can't initialize variable in a chain. They must be initialized separately. Only then can you make a continuous line of assignments: -

ie.
Main(){

int x, y, r, s, e, i;
x = r = y = i = e = s = 4;         // Syntactically Legal
}

main(){

int x = y = r = e = 7;       // Not legal
}

Your compiler SHOULD reject the second example

PS. I think X_SIZE = 58, and Y_SIZE = 59.
0
 

Expert Comment

by:Tarnge
Comment Utility
No, no...Y_SIZE = 58, X_SIZE = 59.
0
 
LVL 2

Expert Comment

by:TaintedGod
Comment Utility
I have found that when i compiled it with different numbers for your SIZE_X/SIZE_Y variables, using printf(), I still got the assertion error, it seems that there is no problem with your compiler or the iostream functions but rather your code has a flaw but I am not exactly sure what it is. Try rewriting the program in a different way, if possible or just changing "assert((y>=0) && (y < Y_SIZE));" , which seems to be the source of the problem.

Good luck.
0
 
LVL 1

Expert Comment

by:hal3000
Comment Utility
I compiled and tested your code in Visual Studio .NET and the output with printf and cout seems identical.

There has been some question on various implementations, so I can't say your implementation will always work.

In the line :
          std::cout << "\n";

I would replace that with:
          std::cout << std::endl;

Sending the char '\n' does not flush the iostream buffer whereas using endl does.

Try it, it may make a difference with your version of the compiler.
0
 

Author Comment

by:eching21
Comment Utility
Hi hal3000,

Apparently endl or '\n' has no effect for me, I still get no output. I even tried cout << "x" << flush, to no avail.

I did another experiment. I ported the exact code over to the wizard generated project for "win32 console" in the Visual Studio IDE, and it works perfectly. Apparently it only refuses to work on the command line compiler (cl.exe).

My command line compile options are cl -EHsc setbit.cpp (I call the program setbit.cpp). I know this seems trivial, but are my options correct? Because as far as I know, the compiler which does the work is the same for both the command line and the visual studio IDE.. but I'm starting to have doubts.. is that assumption correct?

Thanks for your advice!!!
Eugene.
0
 
LVL 1

Accepted Solution

by:
hal3000 earned 200 total points
Comment Utility
I have reproduced your problem using the command line compiler.

After some study, I started looking at the assert functions in setBit.

I assume they are checks to make sure you stay within the bounds of the graphics array.

If so the statement:
       assert ((x>=0) && (x < X_SIZE));
doesn't do the job you want.

Considering that the array bound is X_SIZE/8 what you want is:
      assert ((x>=0) && ((x/8) < (X_SIZE/8)));

Note that the values of x from 57 to 60 would fail this test and you go out of bounds of the array.

Depending on compiler options memory layout would vary and it is unpredictable what the program might do.

There are many default options that vary from the IDE to the command line compiler
0
 

Author Comment

by:eching21
Comment Utility
Hi hal3000,

Thanks so much for your help. I get the problem now :p
Btw, any idea what the general differences are between the default options for the ide and command line compiler?

Thanks once again!
Eugene.
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

This article is meant to give a basic understanding of how to use R Sweave as a way to merge LaTeX and R code seamlessly into one presentable document.
This is an explanation of a simple data model to help parse a JSON feed
The viewer will learn how to synchronize PHP projects with a remote server in NetBeans IDE 8.0 for Windows.
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

763 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

8 Experts available now in Live!

Get 1:1 Help Now