How to figure out C++ syntax from documentation?

Both of the following getline() examples have the same output and work as intended.

The first example if of c style getline() as described in http://www.cplusplus.com/reference/istream/istream/getline/
1
2
3
4
5
6
7
8
9
10
11
12
13
int main()
{
  std::stringstream ss;
  char line[128];           //c_string

  ss << "line1\nline2\n";

  ss.getline(line, 128);    //c syntax
  std::cout << "first line  = " << line << "\n";

  ss.getline(line, 128);
  std::cout << "second line = " << line << "\n";
}


If I wanted to write C++ style getline(), how would one know to write it like this?:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <sstream>

int main()
{
  std::stringstream ss;
  std::string line;         //C++ string

  ss << "line1\nline2\n";

  std::getline(ss, line);   //C++ syntax
  std::cout << "first line  = " << line << "\n";

  std::getline(ss, line);
  std::cout << "second line = " << line << "\n";
}


Both examples have same output:
1
2
first line  = line1
second line = line2


Thank you.
Last edited on
If I wanted to write C++ style getline(), how would one know to write it like this?:

Both of the examples you have shown are both C++ not C.

As you have shown there are two different versions of getline(), one that works with a C-string and another version that uses a std::string. Your first snippet is using a C-string (an array of char terminated by the end of string character ('\0')) and your second snippet is using a C++ std::string.



Now I see, getline() can be one of several functions with the same name.

from http://www.cplusplus.com/reference/istream/istream/getline/
 
ss.getline(line, 128);    //line is C-string 


from http://www.cplusplus.com/reference/string/string/getline/
 
std::getline(ss, line);   //line is C++ std::string 


Thanks jlb.
Topic archived. No new replies allowed.