记录C++与C中一个字符串和字符数组输入不兼容的误区
误区
#include <stdio.h>
#include <string.h>
#include <string>
using namespace std;
int main()
{
string str;
scanf("%s\n",&str);//错误
printf("%s\n",str.c_str() ;
}
这里scanf("%s\n",&str);是错误的,在linux中编译通过,但是数据读入报错
C语言中正确形式
#include <stdio.h>
#include <string.h>
int main()
{
char str[30]; //定义字符数组
scanf("%s",str);//读入数据,str这里指整个数组的地址,故不需要&str
printf("%s\n",str);
}
C++中正确形式
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str;//定义字符串
cin>>str;//读入数据
cout<<str<<endl;
}