在C语言控制台程序中,读取完整行的最简单方法是什么?输入文本的长度可能不固定,我们无法对其内容作出任何假设。
在BSD系统和Android上,您也可以使用fgetln
:
#include <stdio.h>
char *
fgetln(FILE *stream, size_t *len);
就像这样:
size_t line_len;
const char *line = fgetln(stdin, &line_len);
line
没有以空字符结尾,并且在末尾包含\n
(或者是你的平台使用的其他字符)。在流上进行下一个I/O操作后,它将变为无效。
这里是一个最小的实现方法,好处是它不会保留 '\n',但是为了安全起见,您必须给它一个读取的大小:
#include <stdio.h>
#include <errno.h>
int sc_gets(char *buf, int n)
{
int count = 0;
char c;
if (__glibc_unlikely(n <= 0))
return -1;
while (--n && (c = fgetc(stdin)) != '\n')
buf[count++] = c;
buf[count] = '\0';
return (count != 0 || errno != EAGAIN) ? count : -1;
}
测试使用:
#define BUFF_SIZE 10
int main (void) {
char buff[BUFF_SIZE];
sc_gets(buff, sizeof(buff));
printf ("%s\n", buff);
return 0;
}
注意:您的行返回限制为INT_MAX,这已经足够了。
从控制台读取一行的最佳且最简单的方法是使用 getchar() 函数,通过此函数你将逐个将字符存储到数组中。
{
char message[N]; /* character array for the message, you can always change the character length */
int i = 0; /* loop counter */
printf( "Enter a message: " );
message[i] = getchar(); /* get the first character */
while( message[i] != '\n' ){
message[++i] = getchar(); /* gets the next character */
}
printf( "Entered message is:" );
for( i = 0; i < N; i++ )
printf( "%c", message[i] );
return ( 0 );
}
类似这样:
unsigned int getConsoleInput(char **pStrBfr) //pass in pointer to char pointer, returns size of buffer
{
char * strbfr;
int c;
unsigned int i;
i = 0;
strbfr = (char*)malloc(sizeof(char));
if(strbfr==NULL) goto error;
while( (c = getchar()) != '\n' && c != EOF )
{
strbfr[i] = (char)c;
i++;
strbfr = (void*)realloc((void*)strbfr,sizeof(char)*(i+1));
//on realloc error, NULL is returned but original buffer is unchanged
//NOTE: the buffer WILL NOT be NULL terminated since last
//chracter came from console
if(strbfr==NULL) goto error;
}
strbfr[i] = '\0';
*pStrBfr = strbfr; //successfully returns pointer to NULL terminated buffer
return i + 1;
error:
*pStrBfr = strbfr;
return i + 1;
}