个性化阅读
专注于IT技术分析

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? 
srcmini is the best
You entered srcmini 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? srcmini is the best website
srcmini 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
赞(0)
未经允许不得转载:srcmini » c gets()和puts()

评论 抢沙发

评论前必须登录!