c++问题,为什么scanf("%s",str);这样是错的,我定义是string str的

2025-05-10 04:06:41
推荐回答(3个)
回答1:

scanf是C语言,string 是类(C++)。不能直接赋值吧
可以这样:
char buf[1024];
string s;
scanf("%s",buf);
s=buf;
最好不要混合使用C和C++的IO库。直接用cin
#include
#include
using namespace std;
string s;
cin >> s;

回答2:

因为是scanf(%s)你这个是要给一个char*类型的读取,而不是给string类型的,你引用的参数是string类型的,必须是错误的啊

回答3:

既然是C++,就没必要搞得不C,又不是C++的
直接用 cin>>str;

scanf("%s",str); //还需添加头文件 #include