- 接收带空格的一行:
· 如果使用string库,用cin不能接收带空格的string,必须用getline(cin, s);
#include<iostream>
#include<string>
using namespace std;
int main()
{
char a[10000] = "hello world 123";
cout << strlen(a) << endl;
// 遇到空格就逆转
string s;
getline(cin, s);
cout << s << endl;
cout << s.size() << endl;
return 0;
}
· 如果不用string,用geline()给一个字符数组,也没问题。
// 需要多一个位置接收字符串末尾的空格。
//
用cin.getline(str, 16);
char a[10000];
// 输入:hello world 123(15个字符串,但是需要传16)
cin.getline(a, 16);
cout << a << endl;
cout << strlen(a) << endl;
// 使用strlen()输出,仍是长度15。
#include<iostream>
#include<string>
using namespace std;
int main()
{
char a[10000] = "hello world 123";
// strlen()能区分字符串中间的空格和末尾的‘\0’,因为中间的是空格,ASCII:32,而末尾是'\0'不一样
int n = strlen(a);
// 翻转:
int start = 0;
int end = 0;
while(end < n)
{
// end到空格位置
while (end <n && a[end] != ' ')
{
end++;
}
// t存空格位置 或末尾
int t = end;
// end回到空格前一个
end--;
// 交换
cout << "s : "<<start << endl;
cout <<"e: " << end << endl;
while (start < end)
{
char tmp = a[start];
a[start] = a[end];
a[end] = tmp;
start++;
end--;
}
// end 到新起始位置
end = t+1;
// start也到新起始位
start = end;
}
cout << a<<endl;
return 0;
}