C++完全复制要字符串的字符列表,而不会忽略多个空格
C++ copy list of chars to string exactly without ignoring multiple whitespace
我有一个字符列表,L:
{'h','e','l','l','o',' ', ' ',' ', 'm', 'y', ' ', ' ',' ', 'n','a','m','e'};
我想将其复制到字符串中。我想保持三重空格并在下面得到一个字符串 S:
"hello my name"
我试过这个:
string S(L.begin(), L.end());
但它以某种方式删除了三个空格并给了我单个空格,S 变成了:"你好我的名字"。 我尝试一一迭代:
string S = "";
for (auto it = L.begin(); it!=L.end(); it++){
S+=*it;
}
我仍然得到带有单个空格的"你好我的名字"。 我尝试将列表存储在字符向量中,然后通过循环遍历向量并逐个推回字符串变成字符串,但它仍然忽略多个空格。如何告诉计算机将列表的字符逐字复制到字符串中,而不管有多少个连续的空格字符。即使它只是一个空格列表,我也想得到一串空格。有什么帮助吗?
请参阅下面的代码:
int main() {
list<char> L {'h', 'e', 'l', 'l', 'o', ' ', ' ', ' ', 'm', 'y', ' ', ' ', ' ', 'n', 'a', 'm', 'e'};
string S_attempt1(L.begin(), L.end());
string S_attempt2 = "";
for (auto it = L.begin(); it != L.end(); it++){
S_attempt2+=*it;
}
cout << S_attempt1 << endl;
cout << S_attempt2 << endl;
}
对于某些字符串,我得到的字符串是"hello my name"
而不是"hello my name"
这似乎工作正常,并且不会忽略空格:
string convertToString(list<char> lst, int size)
{
string s = "";
for (auto const& i : lst) {
s = s + i;
}
return s;
}
像这样运行这个...
list<char> L = {'h', 'e', 'l', 'l', 'o', ' ', ' ', ' ', 'm', 'y', ' ', ' ', ' ', 'n', 'a', 'm', 'e'};
int L_size = sizeof(L) / sizeof(char);
string s_L = convertToString(L, L_size);
cout << s_L << endl;
。返回预期的输出。
相关文章:
- 2D数组来自文本输入,中间有空格
- Pybind11:将元组列表从Python传递到C++
- 从链接列表c++中删除一个项目
- 如何(从固定列表中)选择一个数字序列,该序列将与目标数字相加
- C++如何通过用户输入删除列表元素
- 读取文件的最后一行并输入到链接列表时出错
- 复制列表初始化的隐式转换的等级是多少
- LNK2038、MSVS2017 MAGMA的原因列表
- 不能在初始值设定项列表中将非常量表达式从类型 'int' 缩小到'unsigned long long'
- 没有为自己的结构调用列表推回方法
- 使用简单类型列表实现的指数编译时间.为什么
- 一对向量构造函数:初始值设定项列表与显式构造
- 标准是否使用多余的大括号(例如 T{{{10}}})定义列表初始化?
- 通过for循环使用用户输入填充列表
- C++:如何使函数只返回作为列表一部分的字符串
- C++完全复制要字符串的字符列表,而不会忽略多个空格
- C++ makefile 将 prefeix 附加到带有空格的双引号项列表中
- 函数调用参数列表 (C++) 中的空格
- 列表中带有空格的字符串
- 输出以空格分隔的列表