Greetings. I am a complete beginner on C++, but have worked in Matlab a lot. I feel embarrassed for even having to ask this, but I think it is a compile problem which is above my head.
#include <iostream>
usingnamespace std;
int main ()
{
int countDown;
cout << "How many greetings do you want?\n";
cin >> countDown;
while (countDown > 0)
{
cout << "Hello!";
countDown = countDown - 1;
}
cout << endl;
cout << "That's all!\n";
return 0;
}
The code outputs nothing. I experimented around with outputs outside of the loop, and it will still do the same thing, i.e. nothing.
I have narrowed it down to the while loop. Any sample programs I have tried using 'while' causes it to just not work. If I comment out the while loop, everything else works fine. I am compiling with Code::Blocks. What am I missing?
Note: A "compile program" is when errors in the code prevent successful compilation. If the compilation succeeds to produce an executable, but running that binary produces unexpected results, then the "runtime error" is usually due to invalid input and/or error in program logic.
Anyway, the code looks valid and the 'cpp.sh' online site compiles and runs the program as expected. Therefore, the question is, how do you run the program?
I'm thinking that this may just be the console closing down problem. Does the console stay open after you input a number? Try using System("PAUSE"); right before return 0;there's a lot of debate about this method, but it's quick and it works.
#include <iostream>
usingnamespace std;
int main ()
{
int countDown;
cout << "How many greetings do you want?\n";
cin >> countDown;
cin.get();
// while (countDown > 0)
// {
// cout << "Hello!";
// countDown = countDown - 1;
// }
//
cout << endl;
// cout << "That's all!";
cin.get();
return 0;
}
Slightly modified as above, this works. As soon as I uncomment [cout << "That's all!";], the runtime gives me the same problem, i.e. it doesn't output anything, and then ends saying "Process terminated with status 1965940563". The exact same thing happens if I uncomment the while loop.
I feel completely stupid that I can't even get a cout line to work, doubly so because I used the exact same command earlier in the program and it did work as expected. Is the problem Code::Blocks and how it is compiling it?
So that means I'm not crazy, something is wrong. I found if I do varying combinations of the cout command, sometimes it will work and other times it causes the same problem. All of this indicates it's a problem with Code::Blocks. Has anyone else ever experienced anything like this? Should I be using a different IDE?
I feel like I'm trying to write an essay, but I can't figure out how to make the pen work...