You need to enable JavaScript to run this app. C++使用stringstream转换char*为string遇空格截断及相关疑问
优惠活动
大模型
产品
解决方案
定价
更多

C++使用stringstream转换char*为string遇空格截断及相关疑问

疑问1:char*类型的date_and_time为什么能存储多个字符
  • char*本质是字符指针,本身仅存储一个内存地址,并不直接存储多个字符
  • ctime()函数返回的指针指向一块预先分配的静态char数组的首地址,这块数组里按顺序存储了时间字符串的所有字符,末尾以\0(空终止符)结束
  • C++中cout输出char时,会自动从指针指向的首地址开始逐个读取字符,直到遇到\0才终止输出,所以看起来是char存储了整个字符串,实际存储字符的是指针指向的连续内存空间。
疑问2:stringstream添加noskipws还是碰到空格停止的原因和解决方案

问题原因

noskipws配置的作用仅为不跳过输入流开头的空白字符,并不会改变>>运算符读取std::string的默认规则:>>读取string时默认碰到任意空白符(空格、换行、制表符等)就会终止读取,这个行为和是否开启noskipws无关,所以你只能读到第一个空格前的"Thu"。

解决方案

方案1:直接用char*构造std::string(最简单,不需要stringstream)

你完全不需要绕stringstream的弯路,直接用C++ string的构造函数就能完成转换:

time_t now = time(0);
char* date_and_time = ctime(&now);
cout << date_and_time << endl;
// 直接用char*构造string即可
string date_and_time_string(date_and_time);
cout << date_and_time_string << endl;

方案2:如果必须使用stringstream,替换>>为getline读取整行

如果你一定要用stringstream做转换,不要用>>运算符,使用getline读取流内的全部内容:

time_t now = time(0);
char* date_and_time = ctime(&now);
cout << date_and_time << endl;
string date_and_time_string;
stringstream ss;
ss << date_and_time;
// 用getline读取整行,不会因为空格停止
getline(ss, date_and_time_string);
cout << date_and_time_string << endl;

内容的提问来源于stack exchange,提问作者Ilija Dončić

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.13 22:03:01