printf gets fgets辨析

本文介绍了C语言中处理字符串的方法,包括使用scanf、fgets、gets等函数的区别,特别强调了安全性和空格处理的重要性,并提供了一个去除字符串中空格的具体实现案例。

一、辨析

 (1)scanf不能读包含有空格的字符串。

 (2)gets和fgets皆读一行内容,可含空格,gets不安全,尽量用fgets。

 (3)注意:若gets和fgets前有输入(如scanf),则要使 用getchar()后再使用gets或fgets,防止将前面的空格读入。

二、facts/关键

 (1)明确各个函数对空格( ‘ ’)的处理。

 (2)想象有个指针指向终端或文件,依次后移。

三、代码

   输入:长度<30的字符串,可包含空格

   输出:去掉空格后的字符串

#include<stdio.h>

#include<stdlib.h>

#define MAX_CHAR_NUM 30

void cut_string(char * p1,char * p2)

{

     int i=0;

     int j=0;

     while(p1[i]!='/0')

     {

       if (p1[i]!=' ')

        {

           p2[j]=p1[i];

           j++;

        }

       i++;

     }

     p2[j]='/0';

}

int main()

{

  char a1[MAX_CHAR_NUM];

  char a2[MAX_CHAR_NUM];                              // (1)allocate memory(data struct)

  printf("please input the string:/n");

  fgets(a1,MAX_CHAR_NUM+1,stdin);                 // (2)initialize original data

  cut_string(a1,a2);                                            // (3)operate 

  printf("%s/n",a2);                                            // (4)print result

}

 

#if 0     //test_code,incomplete

int main()

{

  int num_char;

  char *p1;

  char *p2;

  scanf("%d",&num_char);

  printf("num_char is:%d/n",num_char);

  p1=(char*)malloc(sizeof(char)*(num_char+1));

  p2=(char*)malloc(sizeof(char)*(num_char+1));

 getchar();

  fgets(p1,num_char+1,stdin);

  printf("%s/n",p1);

  cut_string2(num_char,p1,p2);

 printf("%s",p2);

}

#endif

另转

http://linux.about.com/library/cmd/blcmdl3_fgets.htm

NAME

fgetc, fgets, getc, getchar, gets, ungetc - input of characters and strings    

SYNOPSIS

#include <stdio.h
>


int fgetc(FILE *
stream
);

char *fgets(char *
s
, int 
size
, FILE *
stream
);

int getc(FILE *
stream
);

int getchar(void);

char *gets(char *
s
);

int ungetc(int 
c
, FILE *
stream
);

 

DESCRIPTION

fgetc()   reads the next character from   stream  and returns it as an   unsigned char   cast to an int , or   EOF   on end of file or error.

getc()   is equivalent to  fgetc()   except that it may be implemented as a macro which evaluatesstream   more than once.

getchar()   is equivalent to  getc( stdin ) .

gets()   reads a line from  stdin   into the buffer pointed to by  s   until either a terminating newline or  EOF , which it replaces with  '/0' . No check for buffer overrun is performed (see  BUGS   below).

fgets()   reads in at most one less than  size   characters from  stream   and stores them into the buffer pointed to by  s . Reading stops after an  EOF   or a newline. If a newline is read, it is stored into the buffer. A  '/0'   is stored after the last character in the buffer.

ungetc()   pushes  c   back to  stream , cast to  unsigned char , where it is available for subsequent read operations. Pushed - back characters will be returned in reverse order; only one pushback is guaranteed.

Calls to the functions described here can be mixed with each other and with calls to other input functions from the  stdio   library for the same input stream.

For non-locking counterparts, see  unlocked_stdio (3).   

RETURN VALUE

fgetc() ,   getc()  and   getchar()   return the character read as an   unsigned char   cast to an   int or   EOF   on end of file or error.

gets()   and  fgets()   return  s   on success, and  NULL   on error or when end of file occurs while no characters have been read.

ungetc()   returns  c   on success, or  EOF   on error.   

CONFORMING TO

ANSI - C, POSIX.1    

SEE ALSO

read (2),   write (2),   ferror (3),   fopen (3),   fread (3),   fseek (3),   puts (3),   scanf (3), unlocked_stdio (3)

 

 

 

在C语言中,`getchar`、`gets`、`fgets`、`putchar`这几个函数在功能使用场景上存在明显区别: ### 功能用途 - **`getchar`**:用于从标准输入(通常是键盘)读取一个字符。它每次只读取一个字符,包括换行符等特殊字符。例如,若用户输入`abc`并按下回车键,`getchar`第一次调用会返回`a`,再次调用会返回`b`,以此类推,直到遇到文件结束符(EOF)或发生错误 [^2]。 - **`gets`**:用于从标准输入读取一行字符串,直到遇到换行符为止,并且会自动丢弃换行符,将读取的字符串存储在指定的字符数组中。不过,由于`gets`函数不检查输入字符串的长度,可能会导致缓冲区溢出问题,所以在实际编程中不推荐使用 [^1][^3]。 - **`fgets`**:也是用于读取字符串,但它可以从指定的文件流中读取。一般常用从标准输入(`stdin`)读取。`fgets`会读取最多`n - 1`个字符(`n`为指定的缓冲区大小),或者直到遇到换行符或文件结束符,读取的字符串会包含换行符,并在末尾添加字符串结束符`'\0'`。这避免了`gets`函数的缓冲区溢出问题,因此更安全 [^1][^3]。 - **`putchar`**:用于向标准输出(通常是屏幕)输出一个字符。它接受一个整数参数(字符的ASCII码值),并将对应的字符输出到屏幕上 [^2][^3]。 ### 函数原型 - **`getchar`**:`int getchar(void);`,返回值为读取的字符的ASCII码值,如果遇到文件结束符则返回`EOF` [^2]。 - **`gets`**:`char *gets(char *str);`,返回值为指向存储输入字符串的字符数组的指针,如果发生错误或遇到文件结束符则返回`NULL` [^3]。 - **`fgets`**:`char *fgets(char *str, int n, FILE *stream);`,返回值为指向存储输入字符串的字符数组的指针,如果遇到文件结束符或发生错误则返回`NULL` [^3]。 - **`putchar`**:`int putchar(int ch);`,返回值为输出的字符的ASCII码值,如果发生错误则返回`EOF` [^2]。 ### 代码示例 ```c #include <stdio.h> int main() { // getchar示例 int c = getchar(); putchar(c); putchar('\n'); // gets示例(不推荐使用) char str1[100]; gets(str1); puts(str1); // fgets示例 char str2[100]; fgets(str2, sizeof(str2), stdin); fputs(str2, stdout); return 0; } ``` ### 总结 `getchar``putchar`主要用于处理单个字符的输入输出,而`gets``fgets`用于处理字符串的输入。由于`gets`存在安全风险,建议使用`fgets`来替代它进行字符串输入操作。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值