-
istream 实际上是由 typedef定义,有:
typedef basic_istream<char> istream;
其涉及的输入方法有很多,这里说一下getline()函数,其原型为:
istream& getline (char* s, streamsize n );
istream& getline (char* s, streamsize n, char delim );
其中,s为存储输入的字符串缓冲区,n为缓冲区的大小。我们从标准输入中读取字符到缓冲区,知道缓冲区被填满,或者是遇到 delim 字符(一般为'\n')
在很多情况下,我们常常需要对一行输入进行格式化处理,这时可以使用 istringstream,例如:
#include<iostream>#include<string>
#include<sstream>
usingnamespacestd;
intmain()
{
stringstr1,str2;
chartemp[100];
cin.getline(temp,100,'\n');
istringstream isr(string(temp));
isr>>str1>>str2;
cout<<"str1:"<<str1<<"\n";
cout<<"str2:"<<str2<<"\n";
return0;
}
但是事实证明,这样使用会报错,如:
:15: error: no match for 'operator>>' (operand types are 'std::istringstream(std::string) {aka std::basic_istringstream<char>(std::basic_string<char>)}' and 'std::string {aka std::basic_string<char>}')
isr>>str1>>str2;
解决方案是,变成下面这样:#include<iostream>
#include<string>
#include<sstream>
usingnamespacestd;
intmain()
{
stringstr1,str2;
chartemp[100];
cin.getline(temp,100,'\n');
stringstrtemp(temp);
istringstreamisr(strtemp);
isr>>str1>>str2;
cout<<"str1:"<<str1<<"\n";
cout<<"str2:"<<str2<<"\n";
return0;
}
这样就可以了,那么为什么呢?
原因是,编译器认为:
istringstream isr(string(temp));
定义了一个名为isr的函数,而该函数没有定义operator>>所以会有上面的错误。
所以当改成
stringstrtemp(temp);
istringstreamisr(strtemp);
isr>>str1>>str2;
就没有错误了,问题解决。
转载于:https://www.cnblogs.com/getmore/p/istringstream_prbm.html