📜  C gets()和puts()

📅  最后修改于: 2020-10-22 01:44:42             🧑  作者: Mango

C gets()和puts()函数

gets()和puts()在头文件stdio.h中声明。这两个函数都涉及字符串的输入/输出操作。

C gets()函数

gets()函数使用户可以输入一些字符,然后按Enter键。用户输入的所有字符都存储在字符数组中。将空字符添加到数组以使其成为字符串。 gets()允许用户输入以空格分隔的字符串。它返回用户输入的字符串。

宣言

char[] gets(char[]);

使用gets()读取字符串

#include
void main ()
{
    char s[30];
    printf("Enter the string? ");
    gets(s);
    printf("You entered %s",s);
}

输出量

Enter the string? 
javatpoint is the best
You entered javatpoint is the best

gets()函数使用起来很冒险,因为它不执行任何数组边界检查,并且一直读取字符,直到遇到新行(输入)为止。它遭受缓冲区溢出的困扰,可以通过使用fgets()避免它。 fgets()确保读取的字符不超过最大限制。考虑以下示例。

#include
void main() 
{ 
   char str[20]; 
   printf("Enter the string? ");
   fgets(str, 20, stdin); 
   printf("%s", str); 
} 

输出量

Enter the string? javatpoint is the best website
javatpoint is the b

C puts()函数

puts()函数与printf()函数非常相似。 puts()函数用于在控制台上print字符串,该字符串先前已通过使用gets()或scanf()函数读取。 puts()函数返回一个整数值,该整数值表示要在控制台上打印的字符数。因为,它打印用字符串,其光标移动到控制台上的新行的附加字符,整数值返回由放()将总是等于字符数呈现字符串加1英寸

宣言

int puts(char[])

让我们看一个示例,该示例使用gets()读取字符串,并使用puts()在控制台上将其print出来。

#include
#include   
int main(){  
char name[50];  
printf("Enter your name: ");  
gets(name); //reads string from user  
printf("Your name is: ");  
puts(name);  //displays string  
return 0;  
}  

输出:

Enter your name: Sonoo Jaiswal
Your name is: Sonoo Jaiswal