首先,ostringstream、istringstream头文件为:
#include<sstream>
向string中写入数据,当我们构造输出时,希望最后一起输出,使用ostringstream,即我们可以用它来格式化字符串。如caffe源码Blob中有个函数:
inline string shape_string() const { ostringstream stream; for (int i = 0; i < shape_.size(); ++i) { stream << shape_[i] << " "; } stream << "(" << count_ << ")"; return stream.str(); }
举例:
int main(int argc, char* argv[]) { std::ostringstream stream; stream << "Hello"<<" "; stream << "World"; std::cout << stream.str(); getchar(); return 0; }
最后输出:
Hello World
int main(int argc, char* argv[]) { std::istringstream stream("You are the best"); std::string str; while(stream >> str) std::cout << str<<"\n"; getchar(); return 0; }最后输出:
You are the best
#include <string>
istream& getline(istream &in, string &line, char delim);in是一个输入流,如cin、ifstream等。line是将输入流中的字符串放到这个string中,delim是结束字符,默认情况下是‘\n’
000002.jpg car 44 28 132 121逐行读取,并对每行中的字符串逐个处理。
int main(int argc, char* argv[]) { std::string line; std::string word; std::ifstream fin("test.txt"); while (getline(fin, line)) { std::istringstream stream(line); while (stream >> word) std::cout << word << "\n"; } getchar(); return 0; }
atoi(stream.c_str());