Ans*_*oon -1 c++ loops c-strings removing-whitespace
我想编写一个 C++ 程序来接受用户输入的句子并删除所有空格。有错误。
\n输入:ad jq jjwjfwwf
输出:ad\xe2\x96\x80jq
输入:dadad fff
输出:dadad
#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
你太努力了。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
数组。
归档时间: |
|
查看次数: |
204 次 |
最近记录: |