问题两者分别适用于什么情况?
char
相比于getline,char有很多的局限性, char 的大小仅为一字节,
#include<bits/stdc++.h>
using namespace std;
int main( )
{
char a = 'sdaw';
char *p = &a;
cout << a;
return 0;
}
若字符过长会产生如下警告
[Warning] multi-character character constant [-Wmultichar]
[Warning] overflow in implicit constant conversion [-Woverflow]
运行后输出结果
w
--------------------------------
Process exited after 0.04214 seconds with return value 0
请按任意键继续. . .
sizeof(a)可知字符串的长度
当仅需输入具有一字长的字符串时采用char,
#include<bits/stdc++.h>
using namespace std;
int main( )
{
char a;
char *p = &a;
cin >> a;
cout << *p;
return 0;
}
输出结果
w
w
--------------------------------
Process exited after 1.49 seconds with return value 0
请按任意键继续.
geline
当需要遍历输出字符串中某个数值时,用getline
#include<bits/stdc++.h>
using namespace std;
int main( )
{
string s;
getline(cin,s);
int n;
cin >> n;
cout << s[n-1];
return 0;
}
输出结果
I Love Python
3
L
--------------------------------
Process exited after 7.547 seconds with return value 0
请按任意键继续. . .