本文共 3199 字,大约阅读时间需要 10 分钟。
如果有一个文件aaa.txt,有若干行,不知道每行中含有几个整数,要编程输出每行的整数之和,该如何实现?由于cin>>不能辨别空格与回车的差异,因此只能用getline的方式逐行读入数据到string变量中,但在string变量中分离若干个整数还是稍显吃力。一个好的方法是用string流:
#include#include #include using namespace std;int main(){ ifstream in("aaa.txt"); for (string s; getline(in, s);) { int a, sum = 0; for (istringstream sin(s); sin >> a; sum += a); cout << sum << endl; } cin.get(); return 0;}
讲道理,该程序编得有些放肆。本该将istringstream sin(s)单独占一行,结果非但不然,还将sum+=a都缩到循环结构描述的步长部分中去了。这样一来,循环体便为空了,于是,for循环的描述部分后面加上分号便自成独立的语句,但它确实能够完成累计工作。作为单独的循环,最后的“;”还是不能忘记的!!因为程序小,所以可读性还不到受伤害的地步,请读者来见识一下着这种风格。
istringstream是输入string流,它在sstream头文件中说明。该语句类似文件流操作,只不过创建sin流时,其参数为string对象。它是将string的实体看作是一个输入流,因而,sin>>a即是从string流中输入整数到a中,输啊输,一直输到string中的最后一个整数!
string流很有用,有时候要将内容逐个输出到string中,最后才根据计算结果来编排输出格式。这时候,用string流就很管用。
拓展:加入一个文件里面有一些实数,那么按照上述方法求和。
#include#include #include #include using namespace std;int main(){ ifstream in("123.txt"); string i_read; double d_number,sum = 0; while(getline(in,i_read)){ for(istringstream s(i_read);s >> d_number;sum += d_number){ cout << "double number is: " << d_number <
以下是文件 123.txt 中的实数1.23 2.21 3.123 1.21 2.2 .4 1.231 2 31.2 .1 .23
#include#include //istringstream 必须包含这个头文件#include using namespace std; int main(){ string str="i am a boy"; istringstream is(str); string s; while(is>>s) { cout< <
输出结果:
iamaboy
//Example:stringstream、istringstream、ostringstream的构造函数和用法
#include#include int main(){ // default constructor (input/output stream) std::stringstream buf1; buf1 << 7; int n = 0; buf1 >> n; std::cout << "buf1 = " << buf1.str() << " n = " << n << '\n'; // input stream std::istringstream inbuf("-10"); inbuf >> n; std::cout << "n = " << n << '\n'; // output stream in append mode (C++11) std::ostringstream buf2("test", std::ios_base::ate); buf2 << '1'; std::cout << buf2.str() << '\n';}
输出结果:buf1 = 7 n = 7n = -10test1
//Example:stringstream的.str()方法
#include#include int main(){ int n; std::istringstream in; // could also use in("1 2") in.str("1 2"); in >> n; std::cout << "after reading the first int from \"1 2\", the int is " << n << ", str() = \"" << in.str() << "\"\n"; std::ostringstream out("1 2"); out << 3; std::cout << "after writing the int '3' to output stream \"1 2\"" << ", str() = \"" << out.str() << "\"\n"; std::ostringstream ate("1 2", std::ios_base::ate); ate << 3; std::cout << "after writing the int '3' to append stream \"1 2\"" << ", str() = \"" << ate.str() << "\"\n";}
输出结果:
after reading the first int from "1 2", the int is 1, str() = "1 2"after writing the int '3' to output stream "1 2", str() = "3 2"after writing the int '3' to append stream "1 2", str() = "1 23"
注意事项:
由于stringstream构造函数会特别消耗内存,似乎不打算主动释放内存(或许是为了提高效率),但如果你要在程序中用同一个流,反复读写大量的数据,将会造成大量的内存消耗,因些这时候,需要适时地清除一下缓冲 (用 stream.str("") )。
参考链接:
转载地址:http://inpq.baihongyu.com/