Can't run program

Pages: 12
Sorry I should have mentioned that cin.getline() does not clear the stream I don't think, you have to do that yourself.
ive always used the following code to keep the window on the screen.

#include <iostream>
using namespace std;
void main()
{

//your code here



system("pause"); // this will pause the screen and wait for you to press any key to continue.
}

not sure that is what you are looking for in this project, but hope it helps somewhere down the road.
No. NO. NOOOOOOOOO.

And here's why.
http://cplusplus.com/forum/articles/11153/

Acceptable and unacceptable alternatives:
http://www.cplusplus.com/forum/articles/7312/
Last edited on
The problem that you are having is because you are mixxing formatted (>>) and unformatted (getline, ignore) input operations.

Consider the input like an array of characters:
Jimmy\n


With the following program:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <limits>
#include <string>
using namespace std;

int main()
  {
  string name;
  cout << "What is your name? " << flush;
  cin >> name;
  cout << "Hello " << name << "!\n";
  cin.ignore( numeric_limits<streamsize>::max(), '\n' );
  return 0;
  }
the input fails.

Line 10 reads up to the first whitespace character, but does not discard it:
Jimmy\n

The ENTER key ('\n') that the user pressed after typing "Jimmy" is still there. Line 12 reads it and then the program quits.

If you change line 10 to read properly:
 
  getline( cin, name );
then the entire line, including the newline (ENTER key), gets read:
Jimmy\n

Now the program gets to line 12 and finds that there isn't any input to be read -- so it waits for the user to enter some. Press the ENTER key:
Jimmy\n\n

Now line 12 can read that last ENTER key ('\n'):
Jimmy\n\n
and terminate.

The other way to change line 10 is to add an ignore() after the read:
1
2
  cin >> name;
  cin.ignore( numeric_limits<streamsize>::max(), '\n' );

The difference is that getline() reads the entire line, but operator>> only reads up to the first whitespace character. To see the difference, try the program with the first correction and enter "Jimmy Jackson" when it asks a name. Then try the program with the second correction and again enter "Jimmy Jackson" as the name.

Hope this helps.

[edit] Fixed a typo.
Last edited on
Worked after entering the ignore() command.. Find the lanquage rather difficult so I'm probably gonna post a million questions in here.. :)

But great to get some help.. thanks.. :D
Topic archived. No new replies allowed.
Pages: 12