Im just getting back into programming, learned Pascal then C, back in the 80's. So Im going thru this sites turorial. I get to the part of control structures and I start playing around with loops and user input and here's what happened.
I use this code and the console closes after I input the number, and it looks like the program didnt do anything.
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
int a;
cout << "Hello World, ";
cout << "I'm a C++ program" << endl;
When you ask the user to input a variable, then use cin.get (), the cin.get () function takes the enter from the variable. ex:
1 2 3 4 5 6 7 8 9 10 11 12
#include <iostream>
usingnamespace std;
int main ()
{
int a;
cout<< "Please enter a number:\n";
cin>> a;
cout<< "You entered "<< a<< ". Please press ENTER to continue.";
cin.get ();
return 0;
}
When you hit enter when inputting a, cin.get () reads that enter, therefore, when you initialize the variable and remove the user input, there is no enter for the function to read.
There is an article on this site about problems in C++ or something similar by Duoas http://cplusplus.com/forum/articles/7311/, there is a part there about how to pause in that, or you could simply add an extra cin.get ():
1 2 3 4 5 6 7 8 9 10 11 12 13
#include <iostream>
usingnamespace std;
int main ()
{
int a;
cout<< "Please enter a number:\n";
cin>> a;
cout<< "You entered "<< a<< ". Please press ENTER to continue.";
cin.get ();
cin.get (); //this extra will allow for the user to hit enter again to end the program
return 0;
}
This will read the user input for a, then allow for the user to press enter to end the program.
Thank you for the replies. The extra cin.get() works!!
Danny-
I knew it was gunna be something odd like that, I mean the code does look kinda odd, but as I read your explanation it made perfect sense, thank you so much for helping me see it!
Moschops-
I get this error when I try to compile without that header file:
warning C4627: '#include <iostream>': skipped when looking for precompiled header use 1> Add directive to 'StdAfx.h' or rebuild precompiled header
I assumed this had something to do with the symbol problem I was having earlier, but since I downloaded the microsoft symbol library and changed my project paths, Ive had no trouble.