【问题标题】:Difference between std::cin and scanf() applied to string应用于字符串的 std::cin 和 scanf() 之间的区别
【发布时间】:2018-03-24 20:15:26
【问题描述】:

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

【问题讨论】:

  • 因为std::string 不是char* (当您使用%s 时scanf 期望)
  • 使用有效的代码有什么问题? :-)

标签: c++ string scanf cin


【解决方案1】:

scanf 对std::string 一无所知。如果你想读入底层字符数组,你必须写scanf("%s", s.data());。但是请确保使用std::string::resize(number) 确保字符串的底层缓冲区足够大!

一般情况下:不要将scanf 与std::string 一起使用。

如果您想使用 scanf 和 std::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);

【讨论】:

    猜你喜欢
    • 2017-01-29
    • 1970-01-01
    • 2013-05-26
    • 1970-01-01
    • 2016-12-05
    • 1970-01-01
    • 2016-08-16
    • 1970-01-01
    相关资源
    最近更新 更多