如何在 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
How to print a string in C++
提问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 std
namespace using using namespace std;
or prefix both string
and cout
with std::
.
此外,您可能要导入std
使用命名空间using namespace std;
或前缀都string
和cout
带std::
。
回答by hexicle
You need #include<string>
to use string
AND #include<iostream>
to use cin
and cout
. (I didn't get it when I read the answers). Here's some code which works:
您需要#include<string>
使用string
AND#include<iostream>
才能使用cin
and 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.
这可以简单地完成工作,而不是执行您采用的方法。