对于C风格字符串,有如下输入方式:
char info[20];
cin>>info; //read a word;
cin.getline(info,20); // read a line ,discard \n
cin.get(info,20); //read aline ,leave \n in queue
对于string 对象,有两种输入方式:
string stuff;
cin>>stuff; //read a word
getline(cin,stubuf); // read a line discard\n
有两个版本的getline()都有一个参数,
用于指定哪个字符来确定输入的边界:
cin.getine(info,20,':') //read up to :,discard :
getline(stuff,':') ////read up to :,discard :
string 版本的getline()将自动调整string 对象的大小,使之刚好能存储输入的字符
char fname[10];
string lname;
cin>>fname; //could be a problem if input siae >9 characters
cin>>lname; //can read a very very long word
cin.getline(fname,10); //may truncate input
getline(cin,fname) ; //no truncate
string 的版本getline()的自动调节节大小的功能不需要指定输入的大小
string 版本的getline()从输入中读取字符,并将其存储在目标string 中,但有三种情况例外:
1:到达文件尾,这样,输入流的edfbit被设置,以为着方法file(),eof()都将返回true;
2:遇到分界字符,默认为‘\n’,这种情况下,将把分界字符从输入流中删除,而且不存储她;
3:读取的字符到达最大的允许值,它将设置输入流的failbit,这意味着fail()方法返回true; /////Attention !!!
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
我想下面的这段文字也可以解释LZ的问题。
(from MSDN)
string::getline :
Remarks
Note
The class/parameter names in the prototype do not match the version in the header file. Some have been modified to improve readability.
The getline function creates a string containing all of the characters from the input stream until one of the following situations occurs: - End of file. - The delimiter is encountered. - is.max_str elements have been extracted.
Example
Copy Code
// string_getline_sample.cpp
// compile with: /EHsc
// Illustrates how to use the getline function to read a
// line of text from the keyboard.
//
// Functions:
//
// getline Returns a string from the input stream.
//////////////////////////////////////////////////////////////////////
#pragma warning(disable:4786)
#include <string>
#include <iostream>
using namespace std ;
int main()
{
string s1;
cout << "Enter a sentence (use <space> as the delimiter): ";
getline(cin,s1, ' ');
cout << "You entered: " << s1 << endl;;
}
Input
test this
Sample Output
Enter a sentence (use <space> as the delimiter): test this
You entered: test
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The key as follows:
The getline function creates a string containing all of the characters from the input stream until one of the following situations occurs: - End of file. - The delimiter is encountered. - is.max_str elements have been extracted.