c++空格与'\0'

空格与’\0’的输出的样子是一样的

初始化空白字符数组可用
char array[2][2]= {’\0’};

### C++空格的用法及处理方法 #### 输入包含空格的情况 在 C++ 编程中,`std::cin` 默认会在遇到空白字符(如空格、制表符或换行符)时停止读取输入。如果希望程序能够接受带有空格的字符串,则可以使用 `std::cin.get()` 或者 `std::getline()` 函数来实现这一功能[^2]。 以下是通过 `std::cin.get()` 接收带空格字符串的一个例子: ```cpp #include <iostream> using namespace std; int main() { char a[50]; cin.get(a, 50); cout << a << endl; return 0; } ``` 另一种更常用的方式是利用 `std::getline()` 来获取整行输入,这种方法不会因为遇到空格而中断。 ```cpp #include <iostream> #include <string> using namespace std; int main() { string str; getline(cin, str); cout << str << endl; return 0; } ``` #### 删除字符串中的空格 对于需要移除字符串中多余空格的需求,可以通过遍历字符串并跳过空格的方式来完成。下面是一个基于数组操作的例子[^3]: ```cpp #include <iostream> using namespace std; int main() { char s[] = "we are djkjl dd"; int i = 0, j = 0; while (s[i] != '\0') { if (s[i] != ' ') s[j++] = s[i]; i++; } s[j] = '\0'; // 添加字符串终止符 cout << s << endl; return 0; } ``` 此外,在现代 C++ 中推荐使用标准库中的 `std::string` 类型配合算法来进行更加灵活的操作。例如,以下代码展示了如何使用迭代器和成员函数 `erase` 去掉尾部空格[^1]: ```cpp #include <iostream> #include <algorithm> // for iswspace() using namespace std; int main() { string s = "hello world "; auto c = s.end(); while (c != s.begin() && isspace(*--c)); s.erase(++c, s.end()); cout << '"' << s << '"' << endl; // 输出不带尾随空格的结果 return 0; } ``` #### 字符串分割(split) 当涉及到按特定分隔符拆分字符串的任务时,也可以借助自定义逻辑或者第三方工具类库达成目标。这里给出一种简单的手动实现方式作为参考: ```cpp #include <vector> #include <sstream> vector<string> split(const string& str, char delimiter) { vector<string> tokens; stringstream ss(str); string token; while(getline(ss, token, delimiter)) { tokens.push_back(token); } return tokens; } // 使用示例 int main(){ string input="apple orange banana grape"; vector<string> result=split(input,' '); for(auto const &word:result){ cout<< word <<'\n'; } return 0; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值