C printf()一行上有两个字符串?

时间:2014-08-31 23:54:09

标签: c++ c

您好我想知道我是否可以像使用

一样在c ++中输出两个字符串
cout << "hi" << " person";

3 个答案:

答案 0 :(得分:4)

cout一样,printf会将提供给它的任何内容放入输出中。 coutprintf不会添加换行符。

printf("hi");
printf(" person");

输出:

hi person

如果您希望在C中使用单个语句来完成它:

printf( "%s%s", "hi", " person");

对于这两个示例,您必须#include <stdio.h>。 (某些编译器没有必要)。


关于cout的一些额外说明:为什么我们可以在C ++中链接cout

请注意cout << "hi" << " person";只是简写:

cout << "hi";
cout << " person";

以这种方式扩展,与我的第一个带有两个printf调用的示例相差无几。

std::coutstd::ostream的一个实例。并且(简单地说,)std::ostream overloads the << operator使得它可以接受多种类型并返回std::ostream引用。因此<<上的运算符std::ostream(大部分)与此函数相同:

std::ostream& printThingsToOutput(std::ostream& where, string s);

您提供的代码可以像这样打破:

(cout << "hi") << " person";

首先,执行cout << "hi"。它将字符串"hi"发送到输出缓冲区,然后返回cout对象。然后声明的其余部分变为:

cout << " person";

(这也会返回std::ostream引用,该引用会立即被丢弃。)

这是因为重载<<运算符返回相同的std::ostream引用,我们可以按照您的方式将操作链接在一起。

答案 1 :(得分:1)

  • 选项1:

    printf("%s %s", "hi", "person");  
    
  • 选项2:

    printf("%s", "hi" "person");  // Concatenation is only valid for string literals  
    
  • 选项3 :(仅限字符串文字)

    puts("hi" "person");  
    
  • 选项4:

    #include <string.h>
    // ............................
    char longbuff[1000] = "hi";
    strcat(longbuff, "person");
    puts(longbuff);
    

答案 2 :(得分:-1)

您正在寻找的功能名为puts,并在<stdio.h>中声明。