如何在C++中打印字符串

nod*_*nja 64 c++ string printf

我尝试了这个,但它没有用.

#include <string>
string someString("This is a string.");
printf("%s\n", someString);
Run Code Online (Sandbox Code Playgroud)

GWW*_*GWW 113

#include <iostream>
std::cout << someString << "\n";
Run Code Online (Sandbox Code Playgroud)

要么

printf("%s\n",someString.c_str());
Run Code Online (Sandbox Code Playgroud)

  • 我总是喜欢以前的版本. (5认同)
  • 为什么 C 如此烦人且复杂......顺便说一句,谢谢 (2认同)

Thi*_*ter 21

您需要访问底层缓冲区:

printf("%s\n", someString.c_str());
Run Code Online (Sandbox Code Playgroud)

或者更好地使用cout << someString << endl;(你需要#include <iostream>使用cout)

此外,您可能希望std使用using namespace std;或前缀both stringcoutwith 导入命名空间std::.


hex*_*cle 10

你需要#include<string>使用stringAND #include<iostream>来使用cincout.(当我读到答案时,我没有得到它)​​.这里有一些有效的代码:

#include<string>
#include<iostream>
using namespace std;

int main()
{
    string name;
    cin >> name;
    string message("hi");
    cout << name << message;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)


小智 6

你不能在参数中用std :: string调用"printf"."%s"是为C风格的字符串设计的:char*或char [].在C++中你可以这样做:

#include <iostream>
std::cout << YourString << std::endl;
Run Code Online (Sandbox Code Playgroud)

如果你绝对想要使用printf,你可以使用"c_str()"方法给出字符串的char*表示.

printf("%s\n",YourString.c_str())
Run Code Online (Sandbox Code Playgroud)