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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5322216/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 17:54:39  来源:igfitidea点击:

How to print a string in C++

c++stringprintf

提问by node ninja

I tried this, but it didn't work.

我试过这个,但没有用。

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

回答by GWW

#include <iostream>
std::cout << someString << "\n";

or

或者

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

回答by ThiefMaster

You need to access the underlying buffer:

您需要访问底层缓冲区:

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

Or better use cout << someString << endl;(you need to #include <iostream>to use cout)

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

Additionally you might want to import the stdnamespace using using namespace std;or prefix both stringand coutwith std::.

此外,您可能要导入std使用命名空间using namespace std;或前缀都stringcoutstd::

回答by hexicle

You need #include<string>to use stringAND #include<iostream>to use cinand cout. (I didn't get it when I read the answers). Here's some code which works:

您需要#include<string>使用stringAND#include<iostream>才能使用cinand cout。(当我阅读答案时我没有明白)。这是一些有效的代码:

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

int main()
{
    string name;
    cin >> name;
    string message("hi");
    cout << name << message;
    return 0;
}

回答by elmout

You can't call "printf" with a std::string in parameter. The "%s" is designed for C-style string : char* or char []. In C++ you can do like that :

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

#include <iostream>
std::cout << YourString << std::endl;

If you absolutelywant to use printf, you can use the "c_str()" method that give a char* representation of your string.

如果您绝对想使用 printf,则可以使用“c_str()”方法,该方法为您的字符串提供 char* 表示。

printf("%s\n",YourString.c_str())

回答by Perry Horwich

If you'd like to use printf(), you might want to also:

如果您想使用printf(),您可能还想:

#include <stdio.h>

回答by Akash sharma

While using string, the best possible way to print your message is:

使用字符串时,打印消息的最佳方式是:

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

int main(){
  string newInput;
  getline(cin, newInput);
  cout<<newInput;
  return 0;
}


this can simply do the work instead of doing the method you adopted.


这可以简单地完成工作,而不是执行您采用的方法。