簡體   English   中英

C printf()一行上有兩個字符串嗎?

[英]C printf() two strings on one line?

您好,我想知道是否可以像在c ++中那樣一行輸出兩個字符串

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

coutprintf會將提供給它的任何東西都放入輸出中。 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重載<<運算符 ,以便它可以接受幾種類型並返回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:

     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); 

您要查找的函數稱為puts並在<stdio.h>聲明。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM