Input/Output

Hi guys I am messing around with IO,also I am currently taking a course on udemy and I noticed the instructor said that this when you specify a delimiter in the getline function it discards everything after the :

but when I run the following code it prints everything up to the :,discards the delimiter and on the next line prints the population

so for example it prints

population of New Zealand is
4500000
population of UK is
40000000

1
2
3
4
5
6
7
8
9
10
11
ifstream input;

input.open(fileName);

while (input) {
string line;
getline(input, line, ':');

cout << line << endl;

}



but when I run the code below it actually does discard the population,the question is how come the first block of code prints the population and the second block ignores population?

here is the block of code that ignores population the only difference is that I assign the int pop to the contents of input

1
2
3
4
5
6
7
8
9
10
11
12
13
14


while (input) {
		string line;
		getline(input, line, ':');

		int pop;
		input >> pop;

		cout << line << endl;

	}




thanks
Last edited on
Hello adam2016,

First you have to understand that with cin or getline the input does not go directly into the variable, but into a buffer. The contents are extracted in the variable from the buffer.

With cin it will input the contents of what you typed on the keyboard up to the first white space or new line (\n) whichever comes first and if it reaches the (\n) it will leave this in the buffer. The enter key just tells the program that you are finished with what you have typed.

With getline it will take everything up to and including the (\n), but will through away the (\n) leaving the buffer empty. If you use a delimiter with getline it will extract everything up to and including the delimiter character and will through away the delimiter leaving the buffer pointer at the next character in the buffer. So in the end what follows the delimiter is still in the input buffer and can be read either by cin or another getline.

This is handy when you have several fields in one line separated by a delimiter any you need to put the information into different variables by using a delimiter character.

See if this is any help to your understanding
http://www.cplusplus.com/reference/string/string/getline/?kw=getline

Hope that helps,

Andy
wow Andy,top notch answer

that makes sense,is it the same for all streams such as string stream etc?

much appreciated =)
Last edited on
is it the same for all streams such as string stream etc?

yes. A stream is a stream.
Topic archived. No new replies allowed.