getline question

i have a question about getline, to where the function return the value? for example:
1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <string>
using namespace std;

int main () {
  string str;
  cout << "Please enter full name: ";
  //doesn't have a storage variable
  getline (cin,str);
  cout << "Thank you, " << str << ".\n";
}

where the return value stored? in the system?is that related to the istream type that returned from the getline?
getline returns a reference to the it's first argument (cin). This is useful so that you can easily check if the read was successful or not.

1
2
3
4
if (getline (cin,str))
{
	// the line was read without errors!
}
getline() takes in a reference to a string in arugment 2 and fills it within the function. It returns the same istream reference that is passed in as argument 1. This return value is helpful for things like:

1
2
3
4
5
6
7
8
9
ifstream in("InputFile.txt");
if(in.good())
{
  std::string lineTmp;
  while(getline(in,lineTmp))
  {
    // process line string...
  }
}


When the stream has an error, or hits eof, it will break out of the while loop.
The std::getline function which you are using has the following declaration

1
2
3
4
template<class charT, class traits, class Allocator>

basic_istream<charT,traits>&
getline(basic_istream<charT,traits>& is, basic_string<charT,traits,Allocator>& str, charT delim);


So it returns a reference to input stream. At the same time it reads data in the string object that you are passing to it by reference.

As a result you can nesting the function, for example, the following way

1
2
3
4
std::string str;
int x;

std::getline( std::cin, str ) >> x;


Or another example

1
2
3
4
std::string s1;
std:;string s2;

std::getline( std::getline( std::cin, str1 ), str2 );
so it just return the address and thus make the statement true or false? btw

1
2
3
4
std::string str;
int x;

std::getline( std::cin, str ) >> x;


is the cin is flushed so it can accept another entry?
hello?
It returns reference to the input stream which is the first parameter of the function.
So std::getline( std:;cin, str ) return std:;cin.
Last edited on
what about my "second last question"?
I showed you already an example! Why do you do not try it?!
Topic archived. No new replies allowed.