[关闭]
@zhengyuhong 2015-06-10T01:56:30.000000Z 字数 1834 阅读 1247

sstream

未分类


istringstream

  1. typedef basic_istringstream<char> istringstream;
  1. default (1)
  2. explicit istringstream (ios_base::openmode which = ios_base::in);
  3. initialization (2)
  4. explicit istringstream (const string& str,
  5. ios_base::openmode which = ios_base::in);
  6. copy (3)
  7. istringstream (const istringstream&) = delete;
  8. move (4)
  9. istringstream (istringstream&& x);

具体用法与```ifstream````差不多,都是一个输入流

ostringstream

  1. typedef basic_ostringstream<char> ostringstream;
  1. explicit ostringstream (ios_base::openmode which = ios_base::out);
  2. explicit ostringstream (const string& str,
  3. ios_base::openmode which = ios_base::out);

具体用法与ofstream差不多,都是一个输出流

stringstream

  1. template < class charT, // basic_stringstream::char_type
  2. class traits = char_traits<charT>, // basic_stringstream::traits_type
  3. class Alloc = allocator<charT> // basic_stringstream::allocator_type
  4. > class basic_stringstream;

概念与fstream差不多,既是输入流也是输出流,但是stringstream在类型转换方法上大派用场。

stringstream::stringstream

  1. explicit stringstream (ios_base::openmode which = ios_base::in | ios_base::out);
  2. explicit stringstream (const string& str,
  3. ios_base::openmode which = ios_base::in | ios_base::out);

example

  1. ifstream ifs("a.txt");
  2. string str;
  3. stringstream ss;
  4. int n;
  5. while(ifs>>str){ //getline(ifs,str);
  6. ss.str(str);//ss.clear()仅仅是情况状态标识,非清空流中字符
  7. ss>>n;//以空格、回车为分隔符读取流中字符到n
  8. cout<<n<<endl;
  9. }
  10. ifs.close();

当文件a.txt涉及多种类型数据时,如string,int
张三 99
李四 98
...
可以如下读取

  1. ifstream ifs("a.txt");
  2. stringstream ss;
  3. string name;
  4. int age;
  5. string line;
  6. while(getline(ifs,line)){
  7. ss.clear();//需要先情况stringstream 缓存中的流数据,否则下一个name,age依然是上一轮的值
  8. ss.str(line);//将流中数据设置为line,等价于ss.str("");ss<<line;
  9. ss>>name>>age;//以空格、回车为分隔符读取流中数据
  10. cout<<name<<" "<<age<<endl;
  11. }
  12. ifs.close();

C语言的fscanf也可以读入数据,经过测试,4亿条数据,使用C++的getline+stringstream耗时81秒,而fscanf耗时18s,在追求效率是fscanf确实快。

  1. #include <cstdio>
  2. using std::fscanf;
  3. using std::fopen;
  4. using std::fclose;
  5. int main(int argc, char* argv[]) {
  6. FILE* fptr = fopen("a.txt"."r");
  7. char name[80];
  8. int age;
  9. while(fscanf(fptr,"%s%d",name,&age) > 0) {
  10. //do sth
  11. }
  12. fclose(fptr);
  13. return 0;
  14. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注