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

Difference between std::cin and scanf() applied to string

我正在尝试将字符串的第一个字符写入 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];
}

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;
}

虽然这当然只会读到下一个space。所以如果你想阅读整行,你最好使用:

std::string s;
std::getline(std::cin, s);