C语言教程
C语言控制语句
C语言函数
C语言数组
C语言指针
C语言字符串
C语言数学函数
C语言结构
C语言文件处理
C预处理器

C语言gets()和puts()

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

C gets()函数

gets()函数使用户能够输入一些内容。字符,然后按Enter键。用户输入的所有字符都存储在字符数组中。空字符将添加到数组以使其成为字符串。 gets()允许用户输入以空格分隔的字符串。它返回用户输入的字符串。
声明
char[] gets(char[]);
使用gets()读取字符串
#include<stdio.h>
void main ()
{
    char s[30];
    printf("Enter the string? ");
    gets(s);
    printf("You entered %s",s);
}
输出
Enter the string? 
lidihuo is the best
You entered lidihuo is the best
gets()函数使用起来很冒险,因为它不执行任何数组绑定检查,并且一直读取字符,直到遇到新行(输入)为止。它遭受缓冲区溢出的困扰,可以通过使用fgets()避免它。 fgets()确保读取的字符数不超过最大限制。请考虑以下示例。
#include<stdio.h>
void main() 
{ 
   char str[20]; 
   printf("Enter the string? ");
   fgets(str, 20, stdin); 
   printf("%s", str); 
} 
输出
Enter the string? lidihuo is the best website
lidihuo is the b

C puts()函数

puts()函数与printf()函数非常相似。 puts()函数用于在控制台上打印该字符串,该字符串先前已通过使用gets()或scanf()函数读取。 puts()函数返回一个整数值,该整数值表示要在控制台上打印的字符数。由于它将打印带有字符串的附加换行符,将光标移至控制台上的新行,因此puts()返回的整数值将始终等于字符串中存在的字符数加1、
声明
int puts(char[])
让我们看一个示例,该示例使用gets()读取字符串,然后使用puts()在控制台上打印该字符串。
#include<stdio.h>
#include <string.h>  
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
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4