In C, there is a formatted input and output function for scanf and printf, which do not work with std :: string. Are there any similar functions in c ++ that work with strings rather than arrays of characters? For example, if you enter a string of the format "name surname age", how can you immediately assign these values ​​to string and integer variables s, s1, n, respectively?

  • 2
    Need to do it without a "cin" - Dan Nesterov
  • Then why do you need a string ? Work in C. You are not surprised by the lack of a function that calculates, say, the square root directly from a string representation? ... - Harry

4 answers 4

std :: string can be converted to char * and used with printf / scanf. For this there is a method c_str. Here is an example:

 std::string s = "something"; printf("%s\n", s.c_str()); 
  • Does this method work for input too? - Dan Nesterov

In c++ I / O uses cin / cout streams that can be used for this purpose.

 std::string name; std::string surname; int age; std::cout >> name >> surname >> age; 

Analogous to sscanf / sprintf are `stringstream:

 std::stringstream ss; ss << "name surname 666"; std::string name; std::string surname; int age; ss >> name >> surname >> age; 

If you really want exactly scanf / printf , then you need to convert std::string to const char * .

 std::string name = "name"; printf("Name = %s\n", name.c_str()); 

    In general, for formatted input and output, there are very convenient tools _ манипуляторы from the header file <iomanip> , as well as objects and methods of the ostream and istream classes. Apply better manipulators

      For formatted output, such solutions also exist: library boost :: format ( here ); for the Qt library (namely, the QString class ( here and below)) formatted output is implemented; library fmt ; there is even a proposal for a relevant topic in the standard library (based, apparently, on the last ). See more here.