std :: cin和scanf()之间的区别应用于字符串 [英] Difference between std::cin and scanf() applied to string
问题描述
我正在尝试将字符串的第一个字符写入char类型的变量.使用std :: cin(注释掉)可以正常工作,但是使用scanf()会出现运行时错误.当我输入"LLUUUR"时,它会粉碎.为什么会这样呢?使用MinGW.
I am trying to get the first character of a string written to a variable of type char. With std::cin (commented out) it works fine, but with scanf() I get runtime error. It crushes when I enter "LLUUUR". Why is it so? Using MinGW.
#include <cstdio>
#include <string>
#include <iostream>
int main() {
std::string s;
scanf("%s", &s);
//std::cin >> s;
char c = s[0];
}
推荐答案
scanf
对 std :: string
一无所知.如果要读入底层字符数组,则必须编写 scanf(%s",s.data());
.但是请使用 std :: string :: resize(number)
!
scanf
knows nothing about std::string
. If you want to read into the underlying character array you must write scanf("%s", s.data());
. But do make sure that the string's underlying buffer is large enough by using std::string::resize(number)
!
通常:请勿将 scanf
与 std :: string
一起使用.
Generally: don't use scanf
with std::string
.
如果要使用 scanf
和 std :: string
int main()
{
char myText[64];
scanf("%s", myText);
std::string newString(myText);
std::cout << newString << '\n';
return 0;
}
读取后构造字符串.
现在直接在字符串上输入方式:
Now for the way directly on the string:
int main()
{
std::string newString;
newString.resize(100); // Or whatever size
scanf("%s", newString.data());
std::cout << newString << '\n';
return 0;
}
尽管这当然只会读到下一个空格.因此,如果您想阅读整行,则最好使用:
Although this will of course only read until the next space. So if you want to read a whole line, you would be better off with:
std::string s;
std::getline(std::cin, s);
这篇关于std :: cin和scanf()之间的区别应用于字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!