why should i use getchar() function to make it work? [C++]

Status
Not open for further replies.

etiquoe

Member level 1
Joined
Feb 18, 2010
Messages
35
Helped
4
Reputation
8
Reaction score
1
Trophy points
1,288
Location
Indonesia
Visit site
Activity points
1,525
Hi everyone!

i started to learn C++. i'm totally newbie
i'm using Dev C++ compiler.
i tried to run some simple examples from tutorials, like this:


Code C++ - [expand]
1
2
3
4
5
6
7
#include <iostream>
using namespace std;
 
void main () 
{
    cout << “Hello, World!\n”;
}




Or this:


Code C++ - [expand]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
using namespace std;
 
int main ()
{
    int i = 1;
    
    while (i<=257)
    {
          cout << i << "\n";
          ++i;
    }
    
}




No Error when i compiled it, but nothing happen when i ran it. And then i tried to add getchar()function, like this:


Code C++ - [expand]
1
2
3
4
5
6
7
8
#include <iostream>
using namespace std;
 
void main () 
{
    cout << “Hello, World!\n”;
        getchar();
}



and this:


Code C++ - [expand]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
using namespace std;
 
int main ()
{
    int i = 1;
    
    while (i<=257)
    {
          cout << i << "\n";
          ++i;
    }
    
    getchar();
}



Then it worked.

I don't really understand about getchar() function.why the two examples above can work after i add the line (getchar())?
anyone? please?


Regards
 

getchar causes the program to wait for entering a character from user
in fact your programs work but maybe the window close immediately after working once
 

i think you are trying to execute the program from the ide.

instaed , open a command prompt and type the name of your program.exe
(this is without getchar(0 line program)

you will see the output.
 

Status
Not open for further replies.
Cookies are required to use this site. You must accept them to continue using the site. Learn more…