举个栗子:
We are happy--> 输出 "We are happy"
- #include <iostream>
- using namespace std;
- #include <cstddef>
- //length 是字符数组 str 的总容量
- void ReplaceBlank(char *str, int length)
- {
- if (str == nullptr&&length <= 0)
- {
- return;
- }
- int count = 0;
- int i = 0;
- int oldLength = 0;//str 数组中原有长度
- while (str[i] != '\0')
- {
- if (str[i++] == ' ')
- ++count;
- ++oldLength;
- }
- int newLength = oldLength + count * 2;// 加完所有 之后的长度
- int index1 = newLength;
- int index2 = oldLength;
- if (newLength>length)
- return;
- while (index1>= 0 && index2<index1)
- {
- if (str[index2] == ' ')
- {
- str[index1--] = '0';
- str[index1--] = '2';
- str[index1--] = '%';
- --index2;
- }
- else
- {
- str[index1--] = str[index2--];
- }
- }
- }
- int main()
- {
- char str[] = "";
- cin.getline(str,100);// 按行输入
- ReplaceBlank(str, 100);//100
- int i = 0;
- while (str[i] != '\0')
- {
- cout <<str[i];
- i++;
- }
- return 0;
- }
注意: cin.getline(str,100);
第一个参数是字符指针
第二个参数是输入数组最大长度 ('\0'会占据最后一位)
3. 第三个参数是结束字符 (不写默认回车), 结束符不会被输入到数组中
数组名的值是个指针常量, 也就是数组第一个元素的地址. a[300] 是一个数组, a 是一个指向 a[0]
的指针, a+5 是一个指向 a[4] 的指针
cin.getline() 坑点
1. 输入超过自己给 getline() 第二个参数设置的长度, 整个程序的输入就终止了
2.cin.getline() 读到第二个参数的长度或第三个参数符或者回车时结束输入, 丢弃结束符.
比如 cin.getlin(a,5,'-'); 遇到'-'结束输入,'-'和'\0'会被算进第二个参数 5 的个数里面, 但'-'最终会被丢出字符串,(就像'-'凭空消失了一样, a 中不会有, 下一次的 cin>> 也不会读入他, 就像 cin.getline(a,5); 遇到回车默认结束时, 回车被丢出字符串一样);
来源: http://www.bubuko.com/infodetail-3297068.html