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

后端 未结 1 782
天命终不由人
天命终不由人 2021-01-27 09:39

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 crus

1条回答
  •  有刺的猬
    2021-01-27 10:03

    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)!

    Generally: don't use scanf with std::string.

    Another alternative if you want to use scanf and std::string

    int main()
    {
        char myText[64];
        scanf("%s", myText);
    
        std::string newString(myText);
        std::cout << newString << '\n';
    
        return 0;
    }
    

    Construct the string after reading.

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

    0 讨论(0)
提交回复
热议问题