C++ 字符串包含空格和换行 如何去掉
时间: 2023-09-05 16:11:23 浏览: 75
你可以使用 C++ 的字符串处理函数来去掉空格和换行符。下面是一个示例代码:
```cpp
#include <iostream>
#include <string>
#include <algorithm>
int main() {
std::string str = "This is a string with spaces and newlines.\n";
std::cout << "Original string: " << str << std::endl;
// 去掉空格
str.erase(std::remove(str.begin(), str.end(), ' '), str.end());
// 去掉换行符
str.erase(std::remove(str.begin(), str.end(), '\n'), str.end());
std::cout << "Modified string: " << str << std::endl;
return 0;
}
```
这段代码使用了 `std::remove` 函数来移除指定字符,然后使用 `std::string` 的 `erase` 函数来删除这些字符。你可以根据需要修改字符串和删除的字符。运行上述代码后,将输出去掉空格和换行符的字符串。
相关问题
C++ 字符串包 char msg[256]含空格和换行 如何去掉
对于字符数组 `char msg[256]`,你可以使用 C++ 的字符串处理函数来去掉空格和换行符。下面是一个示例代码:
```cpp
#include <iostream>
#include <string>
#include <algorithm>
int main() {
char msg[256] = "This is a message with spaces and newlines.\n";
std::cout << "Original message: " << msg << std::endl;
// 去掉空格
char* end = std::remove(msg, msg + strlen(msg), ' ');
*end = '\0';
// 去掉换行符
end = std::remove(msg, msg + strlen(msg), '\n');
*end = '\0';
std::cout << "Modified message: " << msg << std::endl;
return 0;
}
```
这段代码使用了 `std::remove` 函数来移除指定字符,并将数组末尾的多余字符设置为字符串结束符 `\0`。你可以根据需要修改字符数组和删除的字符。运行上述代码后,将输出去掉空格和换行符的字符串。请注意,如果你的字符数组中没有足够的空间来存储修改后的字符串,可能会导致缓冲区溢出。因此,请确保你的字符数组足够大来存储修改后的字符串。
c++输入带空格字符串不换行继续输入、
可以使用 `getline` 函数来实现输入带空格的字符串不换行继续输入的功能。
示例代码:
```c++
#include <iostream>
#include <string>
using namespace std;
int main() {
string str;
while (getline(cin, str)) {
cout << str << endl; // 输出输入的字符串
}
return 0;
}
```
在上面的代码中,使用 `getline` 函数从标准输入流 `cin` 中读取一行字符串,存储在 `str` 变量中,然后直接输出这个字符串并换行。由于使用了 `while` 循环,所以可以多次输入带空格的字符串,直到用户输入 Ctrl + Z(Windows)或 Ctrl + D(Linux/Mac)结束程序。