Home  >  Article  >  Backend Development  >  What is the usage of puts function in C language?

What is the usage of puts function in C language?

烟雨青岚
烟雨青岚Original
2020-06-16 10:43:1512265browse

What is the usage of puts function in C language?

c语言puts函数用法是什么?

c语言puts函数用法是:puts();

puts()函数用来向标准输出设备(屏幕)输出字符串并换行,具体为:把字符串输出到标准输出设备,将'\0'转换为回车换行。其调用方式为,puts(s);其中s为字符串字符(字符串数组名或字符串指针)。

功能:将字符串输出到终端,puts函数一次只能输出一个字符串,字符串中可以包括转义字符。 

函数原型:int puts(const char *string);

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

初学者要注意以下例子

#include <stdio.h>
int main(void)
{
    char string[] = "This is an example output string\n";
    puts(string);
    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]=&#39;a&#39;;
    string[10]=&#39;\0&#39;;
    puts(string);
    getch();
    return 0;
}

运行就正确了

*注:

(1) puts()函数只能输出字符串, 不能输出数值或进行格式变换。

(2)可以将字符串直接写入puts()函数中。如:

puts("Hello, world!");

(3) puts 和 printf的用法一样,puts()函数的作用与语句“printf("%s\n",s);的作用相同。注意:puts在输出字 符串后会自动输出一个回车符。 

puts()函数的一种实现方案如下:

int puts(const char * string) 
{ 
    const char * t = string; 
    const char * v = string; 
    int i = 0; 
    while(*t!=&#39;\0&#39;) 
    { 
        i++; 
        t++; 
    } 
    int j = 0; 
    for(j;j<=i;j++) 
        putchar((v[j])); 
    putchar(&#39;\n&#39;);
    return 0; 
}

推荐教程:《C语言

The above is the detailed content of What is the usage of puts function in C language?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn