#include <stdio.h> 一、对一个字符的操作 int fgetc(FILE *stream); int getc(FILE *stream); int getchar(void); int ungetc(int c, FILE *stream); 2、getchar() is equivalent to getc(stdin). 3、ungetc() pushes c back to stream, 二、对一个字符串的操作 char *gets(char *s); char *fgets(char *s, int size, FILE *stream); 1、gets() reads a line from stdin into the buffer pointed to by s until either a terminating newline or EOF, which it replaces with a null byte ('\0'). No check for buffer overrun is performed (see BUGS below). warning: the `gets' function is dangerous and should not be used. 2、 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 terminating null byte ('\0') is stored after the
last character in the buffer. ================================================================= 代码示例 #include <stdio.h> #include <errno.h> #include <stdlib.h> #include <string.h> #define MAX_BUF_LEN 1024 int main() { int len = -1; char *buf = (char *)malloc(MAX_BUF_LEN); if(NULL == buf) { perror("calloc error:\n"); return -1; } while(1) { // char *fgets(char *s, int size, FILE *stream); // gets() and fgets() return s on success, and NULL on error or when end of file occurs while no characters have been read. memset(buf, 0, MAX_BUF_LEN); printf("Please input ->:"); fgets(buf, MAX_BUF_LEN, stdin); len = strlen(buf); buf[len - 1] = '\0'; printf("len[%d] out:%s\n", len, buf); } return 0; } |
|
来自: 海漩涡 > 《knowledge》