【问题标题】:C++ copy list of chars to string exactly without ignoring multiple whitespaceC++ 将字符列表复制到字符串,而不忽略多个空格
【发布时间】:2020-09-14 19:54:12
【问题描述】:

我有一个字符列表,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"

【问题讨论】:

  • 您的列表中包含这样的空格 ' '。首先,您应该从列表中删除空格。
  • “字符列表”是什么意思。是array 吗?那没有.begin().end() 成员。请出示minimal reproducible example
  • 显示L 的声明并显示您用来验证它是否正在删除空格的方法。您是否在调试器中查看它?打印出来?我们需要一个minimal reproducible example
  • This works 带有适当声明的L。你在别处犯了错误。
  • 我有一个字符列表,L -- 尝试存储列表 -- 我如何告诉计算机复制列表的字符 -- 这个“列表”是什么?除非您的意思是 std::list,否则标准 C++ 中没有“列表”之类的东西。

标签: c++ string list char whitespace


【解决方案1】:

这似乎工作正常并且不会忽略空格:

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;

...返回预期的输出。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-02
    • 2022-01-19
    • 1970-01-01
    • 2015-09-14
    • 1970-01-01
    • 1970-01-01
    • 2021-04-28
    • 2015-10-01
    相关资源
    最近更新 更多