stringstream的一个空格引起的错误
2011-05-06 15:24
225 查看
// TestIO.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <sstream> #include <string> #include <iostream> using namespace std; int _tmain(int argc, _TCHAR* argv[]) { int val1 = 512; int val2 = 1024; ostringstream format_message; format_message << "va1:" << val1 << "/n" << "val2:" << val2 << "/n"; istringstream input_string(format_message.str()); string dump; input_string >> dump >> val2 >> dump >> val1; cout << dump << endl; cout << val1 << " " << val2; return 0; }
这段代码的意思是用ostringstream存储一个string,它的内容可能来自文本,本例中是这样的
val1: 512/nval2: 1024
然后打算把它输出,用意是取出512和1024这两个数值。具体的作法是用format_message.str()取出string类型的值然后用它来构造一个istringstream,再由这个istringstream输入到val1和val2中(其过程是交换了这两个值),使它们获得新的值。
【问题描述】
发现dump里的值是val1:512,而val1和val2的值并没有交换
【分析过程】
设置断点后debug,发现dump第一次读取的值就是val1:512,这说明istringstream并没有把val1和512区分开来。
考虑istringstream区分string的标记大致有 空格、回车、制表 等,再看我的程序
format_message << "va1:" << val1 << "/n" 。。。。。。。
这里的 "va1:" 没有空格
【修改】
format_message << "va1: " << val1 << "/n" << "val2: " << val2 << "/n";
【思考】
这样看来dump第一次接收的值是val1:512,然后val1接收val2: 1024,此时由于类型不是匹配,接收失败,接下来dump和val2都没有可以接收的内容,所以val1和val2的值并没有交换
相关文章推荐
- Java Web 中防止同时操作一个数据引起错误
- 剔除一个string里的空格
- 一个stmt多个rs进行操作引起的ResultSet已经关闭错误
- DELPHI 调用webservice一个安全问题引起的内存地址错误
- 一个Hibernate中映射文件里设置引起的错误[续]
- [RK3288][Android6.0] 调试笔记 --- 空格引起的编译错误
- JSP - Filter引起的一个奇怪错误 - 重复jsp内容
- C#控制台基础 将一个string数组合并成一个string字符串,以空格隔开
- 关于Resources.Load(string, type)的一个错误
- istringstream 不能按空格分割字符串原因之一
- 一个小错误: deprecated conversion from string constant to char*错误的修改
- php simple_html_dom 一个iconv错误引起解析中断的问题,貌似内存溢出
- stringstream 与空格 (大家讨论一下代码结果的原因)
- 记一个合并代码导致的错误(自定义控件路径改变引起找不到类)
- 一个简单程序引起的反思----算字符串最后一个单词的长度,单词以空格分割
- 一个空格引起的访问404问题
- radio js toString bindable disabled evevt.srcElement. 多个空格变成一个空格 js格式化时间 [Bindable(true)] jquery img select
- ES _all、_source的使用——_all字段连接所有字段的值构成一个用空格(space)分隔的大string而被analyzed和index,document主体保存在_source中
- 一个引号引起的血案,ORACLE SQL 分页语句的错误
- 一个小配置错误引起的大问题