Why use c strings in c++?

后端 未结 18 2174
终归单人心
终归单人心 2021-02-07 04:12

Is there any good reason to use C-strings in C++ nowadays? My textbook uses them in examples at some points, and I really feel like it would be easier just to use a std::string

18条回答
  •  难免孤独
    2021-02-07 04:34

    Given the choice, there is generally no reason to choose primitive C strings (char*) over C++ strings (std::string). However, often you don't have the luxury of choice. For instance, std::fstream's constructors take C strings, for historical reasons. Also, C libraries (you guessed it!) use C strings.

    In your own C++ code it is best to use std::string and extract the object's C string as needed by using the c_str() function of std::string.

提交回复
热议问题