了解 fgets 错误处理,在 stdin 中传递 >sizeof(string) 时

问题描述 投票:0回答:1

这个简单的根本性错误我已经坐了一段时间了。 我们如何避免标准输入中的字符串大于定义的 sizeof(sring)。这里 sizeof(stdin_passed) > sizeof(word_new)。此外,我们仅限于使用、ferr 和/或 feof。

提前致谢

编辑: 提示是没有 角色,我会尝试与它合作


int main() {

    char word_new[42];

    while(1) {
        /*help needed here: ouput is Segmentation Error*/

        if (fgets(word_new, sizeof(word_new), stdin) == NULL){
            // error occurs, thus use perror
            if(ferror(stdin)){
                perror("error occured in stdin");
                exit(1);
            }
            // no error and only EOF reached
            break;
        }
c fgets feof ferror
1个回答
0
投票

您无法避免错误的输入。您的程序可以“检测”它并做出响应。通常最正确的响应是... 终止(带有错误消息)! 获取用户输入字符串通常应如下所示:

// String space for input is reasonable, but not unlimited: char s[100]; // Attempt to get input -- fail if not obtained if (!fgets( s, sizeof(s), stdin )) complain_and_quit(); // Verify you got an entire line of input -- fail if not obtained char * p = strpbrk( s, "\n\r" ); if (!p) complain_and_quit(); *p = '\0';

换句话说,让你的程序要求输入有效才能成功。

© www.soinside.com 2019 - 2024. All rights reserved.