Odd error?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include "stdafx.h"
#include <iostream>
using namespace std;


int _tmain(int argc, _TCHAR* argv[])
{
    char buffer[ 30 ] = { 0 };
    int c = 0;

    //un-comment the following line to change the output of 'buffer'
    //cout << "Num entry: "; cin >> c;

    cout << "Enter something ( '.' delimiter ): ";
    cin.getline( buffer, 30, '.' );

    cout << "You entered: " << buffer << endl;

    //system( "pause" );

return 0;
}


Could anyone spread some light as to why asking for input before string/char input, that the new string/char seems to end up having a '\n' charactor at the beginning

For some reason, this makes the entered string, carrage return before the actual string.
i.e. buffer = "\nI was here".

I've tried this many ways. If the number input is after the getline(), then the string/char is ok.

If the number input is anywhere before getline(), even in another function, it will still have a '\n' at the start of the string/char. ( I'm guessing it's an '\n' ).

This happens with any type of 'cin >>' ( cin >> int; cin >> char; ... ).

Can anyone explain as to why this happens? Or at least how I can stop it happening?


I did find a way passed it by doing the following:

1
2
3
4
5
6
7
8
9
10
11
void Player::setName( char *n )
	{ 
		n++;

		sizeOfText = strlen( n ) + 1;

		name = new char[ sizeOfText ];

		if( name )
			strcpy( name, n );
	}


By incrementing the *n pointer by one, taking off the '\n'.

But this doesn't really sort out the problem in other programs I've tried to create.

Thanks for any help.
cin >> c;

reads an integer. A carriage return is not an integer, so the read of the integer leaves the carriage
return in the input buffer. The read of the string then sees the carriage return as the first character
of input.


(One way to stop this is after you've read the integer, read all characters up to an including the next
newline. You can do this with getline() or cin.ignore()).
i've never quite understood what you folks mean by
read all characters up to an including the next
newline.
What are we reading from? The input buffer? And how do we access that? Does cin have a member called input buffer?
Read this. In fact I'm sure you will find most of section 15 to be helpful for stdio issues.
http://www.parashift.com/c++-faq-lite/input-output.html#faq-15.6
Thanks alot jsmith!! Much appreciated. And thanks for the info Kempo.
getline( ftw );
Topic archived. No new replies allowed.