複製鏈接
請複製以下鏈接發送給好友

puts

鎖定
puts()函數用來向標準輸出設備(屏幕)輸出字符串並換行,具體為:把字符串輸出到標準輸出設備,將'\0'轉換為回車換行。其調用方式為,puts(s);其中s為字符串字符(字符串數組名或字符串指針)。
外文名
puts
功 能
 送一字符串到流stdout中
用 法
int puts(const char *string);
調用方式為
puts(s);

puts功 能

將字符串輸出到終端,puts函數一次只能輸出一個字符串,字符串中可以包括轉義字符 [1] 

puts用 法

int puts(const char *string);

puts程序例

#include <stdio.h>
int main(void)
{
    char string[] = "This is an example output string\n";
    puts(string);
    return 0;
}

初學者要注意以下例子
#include <stdio.h>
#include <conio.h>
int main(void)
{
    int i;
    char string[20];
    for(i=0;i<10;i++)
        string[i]='a';
    puts(string);
    getch();
    return 0;
}

從此例中可看到puts輸出字符串時要遇到'\0’也就是字符結束符才停止,如上面的程序加上一句 string[10]='\0';
#include <stdio.h>
#include <conio.h>
int main(void)
{
    int i;
    char string[20];
    for(i=0;i<10;i++)
        string[i]='a';
    string[10]='\0';
    puts(string);
    getch();
    return 0;
}
運行就正確了

putsprintf、putchar和puts函數的區別

printfputchar和puts函數均為輸出函數。printf函數可輸出各種不同類型的數據,putchar函數只能輸出字符數據,而puts函數可輸出字符串數據。
puts(s)的作用與語句printf("%s”,s)的作用基本相同,puts()函數只能輸出字符串,不能輸出數值或進行格式變換。puts()函數在輸出字符串後會自動輸出一個回車符。 [2] 
例如printf(”%c”,'A') 與putchar('A')都是輸出一個字符A。
printf(”%c\n”,”F'’)與puts(”F”)都是輸出字符F並換行。 [3] 

puts説明

(1) puts()函數只能輸出字符串, 不能輸出數值或進行格式變換。
(2)可以將字符串直接寫入puts()函數中。如:
puts("Hello, world!");
(3) puts 和 printf的用法一樣,puts()函數的作用與語句“printf("%s\n",s);的作用相同。注意:puts在輸出字 符串後會自動輸出一個回車符。 [4] 
puts()函數的一種實現方案如下:
int puts(const char * string) 
{ 
    const char * t = string; 
    const char * v = string; 
    int i = 0; 
    while(*t!='\0') 
    { 
        i++; 
        t++; 
    } 
    int j = 0; 
    for(j;j<=i;j++) 
        putchar((v[j])); 
    putchar('\n');
    return 0; 
}
參考資料
  • 1.    楊健沾 ,汪同慶.C語言程序設計:武漢大學出版社,2009.01:190
  • 2.    C語言程序設計.甘勇 ,李曄 ,盧冰:中國鐵道出版社,2015.09:171
  • 3.    鄒北驥 ,黃霞 ,陳再良.C語言程序設計教程:天津大學出版社,2011.08:29
  • 4.    張越男 ,高妍.C語言程序設計案例教程:北京交通大學出版社,2011.06:37