“printf” on strings prints gibberish

前端 未结 4 1878
执笔经年
执笔经年 2020-12-06 17:05

I\'m trying to print a string the following way:

int main(){
    string s(\"bla\");
    printf(\"%s \\n\", s);
         .......
}

but all I

相关标签:
4条回答
  • 2020-12-06 17:22

    Because %s indicates a char*, not a std::string. Use s.c_str() or better still use, iostreams:

    #include <iostream>
    #include <string>
    
    using namespace std;
    
    int main()
    {
      string s("bla");
      std::cout << s << "\n";
    }
    
    0 讨论(0)
  • 2020-12-06 17:26

    You need to use c_str to get c-string equivalent to the string content as printf does not know how to print a string object.

    string s("bla");
    printf("%s \n", s.c_str());
    

    Instead you can just do:

    string s("bla");
    std::cout<<s;
    
    0 讨论(0)
  • 2020-12-06 17:30

    I've managed to print the string using "cout" when I switched from :

    #include <string.h>
    

    to

    #include <string>
    

    I wish I would understand why it matters...

    0 讨论(0)
  • 2020-12-06 17:40

    Why don't you just use

    char s[]="bla";
    
    0 讨论(0)
提交回复
热议问题