我经常会错用这个函数。它的原型是
getline(is, s)
这个函数的解释说明是:reads a line of input from is into s. Returns is.
注意哦,返回的是is的值,而非s的值。
c++primer里对getline的再解释是这个样子的:
using getline to read an entire line.
sometimes we do not want to ignore the whitespace in our input. In such cases, we can use the getline function instead of the >> operator. The getline function takes an input stream and a string. This function reads the given stream up to and including the first newline and stores what it read–not including the newline—in its string argument. After getline sees a newline, even if it is the first character in the input, it stops reading and returns. If the first character in the input is a newline, then the resulting string is the empty string.
下面用一个例子来巩固一下对这个函数的理解:
exercise 3.6: use a range for to change all the characters in a string to x.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str;
while (getline (cin, str));
cout << "before change string is: " << str << endl;
cout << "string size is: " << str.size() << endl;
//cout << "string length is" << str.strlen() << endl;
for (int i = 0; i < str.size(); i++)
{
str[i] = 'X';
}
cout << str;
return 0;
}