C++ 程序从用户输入中删除句子的所有空格

Ans*_*oon -1 c++ loops c-strings removing-whitespace

我想编写一个 C++ 程序来接受用户输入的句子并删除所有空格。有错误。

\n

输入:ad jq jjwjfwwf

\n

输出:ad\xe2\x96\x80jq

\n

输入:dadad fff

\n

输出:dadad

\n
#include<iostream>\nusing namespace std;\n//using while loop to copy string\nint main(){\n    int i=0;\n    int j=0;\n    char c[30];\n    char cc[30];\n    char ccc[30];\n    cin.getline(c,30);\n    while (c[i]!='\\0')\n    {\n        cc[i]=c[i];\n        i++;\n    }\n    cc[i]='\\0'; \n    for (j=0;j<i;j++){\n        if (c[j]==' ')\n        {\n            continue;\n        }\n        if (c[j]=='\\0')\n        {\n            break;\n        }\n        ccc[j]=c[j];        \n    }\n    ccc[j]='\\0';\n    cout<<cc<<'\\n'<<ccc<<endl;\n    return 0;\n}\n
Run Code Online (Sandbox Code Playgroud)\n

joh*_*ohn 6

你太努力了。C++ 具有可以为您执行此操作的类和库代码

#include <iostream>
#include <string>
#include <algorithm>

int main()
{
    std::string s;          // a string for the sentence
    getline(std::cin, s);   // get the sentence from the user
    s.erase(std::remove(s.begin(), s.end(), ' '), s.end()); // remove the spaces
    std::cout << s << '\n'; // print the result
}
Run Code Online (Sandbox Code Playgroud)

如您所见,如果您使用该std::string类型,则删除所有空格只需一行代码。

即使您尝试练习编写循环,您仍然应该使用数组std::string而不是char数组。

  • 使用 C++20,我们得到了更加简化的 [`std::erase(s, ' ');`](https://en.cppreference.com/w/cpp/string/basic_string/erase2) (2认同)