我试过了,但没有奏效。如何在C++中打印一个字符串
#include <string>
string someString("This is a string.");
printf("%s\n", someString);
我试过了,但没有奏效。如何在C++中打印一个字符串
#include <string>
string someString("This is a string.");
printf("%s\n", someString);
#include <iostream>
cout << someString << "\n";
或
printf("%s\n",someString.c_str())
我总是喜欢前版本。 – 2011-03-16 07:34:58
它更好用:std :: cout << someString <<“\ n”; – ChaosPredictor 2017-06-26 15:41:56
您需要访问底层缓冲区:
printf("%s\n", someString.c_str());
或者更好地利用cout << someString << endl;
(你需要#include <iostream>
使用cout
)
此外,您可能要导入使用using namespace std;
的std
命名空间或者前缀string
和cout
与std::
。
如果您想使用printf()
,你可能也想:
#include <stdio.h>
'#include
不能称之为 “printf” 上有一个std ::字符串参数。 “%s”设计用于C风格的字符串:char *或char []。 在C++中,你可以做这样的:
#include <iostream>
std::cout << YourString << std::endl;
如果绝对想用printf,你可以使用该给你的字符串的一个char *表示的“c_str()”方法。
printf("%s\n",YourString.c_str())
你需要#include<string>
和#include<iostream>
(我没有得到它,当我读到的答案)。这里有一些代码可以工作:
#include<string>
#include<iostream>
using namespace std;
int main()
{
string name;
cin >> name;
string message("hi");
cout << name << message;
return 0;
}
“没有工作” - 为什么不告诉我们一个错误或什么不工作? (尽管在这种情况下它很明显 - 但是你也可能有编译器错误,因为你不会导入'std'命名空间) – ThiefMaster 2011-03-16 07:32:46
重复:http://stackoverflow.com/questions/3634766/c-printf-on -strings-prints-gibberish – 2011-03-16 13:58:45