2014-01-09 115 views
0

我想编写一个函数来读取stdin中的数据。该功能将被其他功能调用以提示用户输入数据。丢弃标准输入流缓冲区中的无关字符

void read_data(void) { 
    // prompt the user by printing a message 
    // printf("enter data:\n"); 

    int a; 
    char name[40]; 
    scanf("%d", &a); 

    // prompt for input again 

    scanf("%39[^\n]", name); 

    // do something with the data 
} 

为了使功能read_data正常工作,不应该有在stdin流缓存器的任何多余的字符,即,它应该是空的。该函数不知道在最后一次调用中输入了什么,并且输入缓冲区中可能存在整数和字符。

如何确保函数read_data正常工作?

+0

只需使用'fgets()'并逐行读取输入。比scanf()好得多(包括安全!)。 – 2014-01-09 17:44:12

+0

以后不会调用'fgets()'会遇到同样的问题吗?如果输入字符串比我们传递给'fgets'的缓冲区长?接下来'fgets'调用将从'stdin'缓冲区开始读取。 – ajay

+1

'fgets()'吃掉所有尾随的换行符。如果你传递了一个尺寸为'LINE_MAX'的杂物,那么它就能保持任何一行。 – 2014-01-09 18:30:03

回答

1
void read_data(void) { 

// prompt the user by printing a message 
// printf("enter data:\n"); 

int a,c; 
char name[40]; 
scanf("%d", &a); 
while((c=getchar()) != '\n'); 
// prompt for input again 

scanf("%39[^\n]", name); 
while((c=getchar()) != '\n'); 
// do something with the data 
} 

使用与

while((c=getchar()) != ' ' && c != '\t' && c != '\n'); 

第一scanf函数因此,如果给定的字符是“\ n”,那么getchar函数获得字符,并检查它是否是新行,如果它是新行,如果转会还有一点,它会到达换行符,因此stdin流缓冲区被清除。

+0

如果在没有提示用户输入的情况下存在非空白字符,则第一个'scanf'调用将静默地从缓冲区中读取。 – ajay

+0

在第一个scanf函数下使用下面的代码。 – Chandru

+0

以及如果输入缓冲区为空?然后你必须输入一个空白字符才能退出while循环。 – ajay