Solved

How does iostream cout really work?

Posted on 2004-04-08
16
1,676 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
ID: 10784839
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
ID: 10784859
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
ID: 10784914
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
Gigs: Get Your Project Delivered by an Expert

Select from freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely and get projects done right.

 
LVL 16

Expert Comment

by:warturtle
ID: 10785012
Hi,

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

Regards,

Warturtle
0
 

Author Comment

by:eching21
ID: 10785537
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
ID: 10785554
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
ID: 10785844
you could always macro cout to std::cout ...
0
 

Expert Comment

by:Tarnge
ID: 10785870
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
 

Author Comment

by:eching21
ID: 10785952
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
ID: 10786088
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
ID: 10786117
No, no...Y_SIZE = 58, X_SIZE = 59.
0
 
LVL 2

Expert Comment

by:TaintedGod
ID: 10788362
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
ID: 10794790
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
ID: 10795851
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
ID: 10796297
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
ID: 10796481
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

Gigs: Get Your Project Delivered by an Expert

Select from freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely and get projects done right.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
allswap challenge 6 96
Windows Service to Receive TCP Packets 4 145
Advice on Xojo as a development tool over VB. 4 55
How to Convert a Quote to an Order in SalesForce 2 39
Whether you’re a college noob or a soon-to-be pro, these tips are sure to help you in your journey to becoming a programming ninja and stand out from the crowd.
This article will inform Clients about common and important expectations from the freelancers (Experts) who are looking at your Gig.
The viewer will learn how to use NetBeans IDE 8.0 for Windows to connect to a MySQL database. Open Services Panel: Create a new connection using New Connection Wizard: Create a test database called eetutorial: Create a new test tabel called ee…
The viewer will learn how to use and create new code templates in NetBeans IDE 8.0 for Windows.

776 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