应用于字符串的std :: cin和scanf()之间的区别

时间:2018-03-24 20:15:27

标签: c++ string scanf cin

我试图将字符串的第一个字符写入char类型的变量。使用std :: cin(注释掉)它工作正常,但是使用scanf()我得到运行时错误。当我进入“LLUUUR”时它会粉碎。为什么会这样?使用MinGW。

#include <cstdio>
#include <string>
#include <iostream>
int main() {
    std::string s;
    scanf("%s", &s);
    //std::cin >> s;
    char c = s[0];
}

1 个答案:

答案 0 :(得分:0)

scanfstd::string一无所知。如果要读入基础字符数组,则必须编写scanf("%s", s.data());。但是请确保使用std::string::resize(number)

确保字符串的底层缓冲区足够大

通常:不要将scanfstd::string一起使用。

另一种选择,如果您想使用scanfstd::string

int main()
{
    char myText[64];
    scanf("%s", myText);

    std::string newString(myText);
    std::cout << newString << '\n';

    return 0;
}

阅读后构造字符串。

现在直接在字符串上的方式:

int main()
{
    std::string newString;
    newString.resize(100); // Or whatever size   
    scanf("%s", newString.data());

    std::cout << newString << '\n';

    return 0;
}

虽然这当然只能读到下一个空格。因此,如果您想阅读整行,那么您最好使用:

std::string s;
std::getline(std::cin, s);
相关问题