[英]C printf() two strings on one line?
您好,我想知道是否可以像在c ++中那样一行输出两个字符串
cout << "hi" << " person";
Just as same as cout
, printf
will put anything that's supplied to it into the output. 与cout
, printf
会将提供给它的任何东西都放入输出中。 cout
or printf
does not add newlines. cout
或printf
不会添加换行符。
printf("hi");
printf(" person");
Output: 输出:
hi person
If you are looking to accomplish it with a single statement in C: 如果您希望使用C中的单个语句来完成此任务:
printf( "%s%s", "hi", " person");
For both examples, you will have to #include <stdio.h>
. 对于这两个示例,您都必须#include <stdio.h>
。 (Not necessary for some compilers). (对于某些编译器不是必需的)。
cout
: Why can we chain cout
in C++? 关于cout
一些额外说明:为什么我们可以在C ++中链接cout
? Please note that cout << "hi" << " person";
请注意cout << "hi" << " person";
is just shorthand for: 只是:
cout << "hi";
cout << " person";
Expanded this way, it is not much different from my first example with two printf
calls. 通过这种方式扩展,与我的第一个示例(带有两个printf
调用)没有太大不同。
std::cout
is an instance of std::ostream
. std::cout
是std::ostream
的实例。 And (simply put,) std::ostream
overloads the <<
operator such that it can accept a several types and return a std::ostream
reference back. 并且(简单地说) std::ostream
重载<<
运算符 ,以便它可以接受几种类型并返回std::ostream
引用。 So the operator <<
on std::ostream
is (mostly) same as this function: 因此, std::ostream
上的运算符<<
(在大多数情况下)与此函数相同:
std::ostream& printThingsToOutput(std::ostream& where, string s);
The code you supplied can be broken like this: 您提供的代码可以像这样破坏:
(cout << "hi") << " person";
First, cout << "hi"
is executed. 首先,执行cout << "hi"
。 It send the string "hi"
to the output buffer, and then returns the cout
object. 它将字符串"hi"
发送到输出缓冲区,然后返回cout
对象。 Then the rest of the statement becomes: 然后,该语句的其余部分变为:
cout << " person";
(This also returns a std::ostream
reference, which is discarded immediately.) (这还会返回一个std::ostream
引用,该引用将立即被丢弃。)
It is because of the fact that overloaded <<
operator returns the same std::ostream
reference that we can chain the operations together in the manner you have done. 由于重载<<
运算符会返回相同的std::ostream
引用,因此我们可以按照您完成的方式将这些操作链接在一起。
Option 1: 选项1:
printf("%s %s", "hi", "person");
Option 2: 选项2:
printf("%s", "hi" "person"); // Concatenation is only valid for string literals
Option 3: (for string literals only) 选项3 :(仅适用于字符串文字)
puts("hi" "person");
Option 4: 选项4:
#include <string.h> // ............................ char longbuff[1000] = "hi"; strcat(longbuff, "person"); puts(longbuff);
您要查找的函数称为puts
并在<stdio.h>
声明。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.