简体   繁体   English

检查输入以查看用户是否输入了control -d

[英]Checking input to see if user has entered control-d

Pretty new to C, and I have what may be a pretty simple question. 对于C来说还很陌生,我有一个可能很简单的问题。 I am writing a program in C which reads a series of strings from the user. 我正在用C编写一个程序,该程序会从用户那里读取一系列字符串。 The program is supposed to do something with these strings after the user indicates that he is done entering strings. 在用户指示他已经完成输入字符串之后,程序应该对这些字符串进行处理。 He does this by entering "Ctrl-D". 他通过输入“ Ctrl-D”来做到这一点。

I'm having trouble figuring out how to check if the user has entered "Ctrl-D". 我在弄清楚如何检查用户是否输入“ Ctrl-D”时遇到麻烦。 From my initial research, it appears as though Ctrl-D is supposed to have something to do with End of File, which, it appears is not a character that I can easily check against. 从我的初步研究来看,似乎Ctrl-D应该与文件结尾有关,这似乎不是我可以轻松检查的字符。

I'm trying to read these strings via scanf. 我正在尝试通过scanf读取这些字符串。 I have the following code (please ignore the initial strings array that eventually get returned. I know it does nothing at the moment. 我有以下代码(请忽略最终返回的初始字符串数组。我知道当前它什么也不做。

char **get_fragments_from_user(){
    char *strings[20000];

    char tempstring[1001];
    while(true){
        printf("\n> ");
        scanf("%s", &tempstring);
        printf("\n Recorded %s", tempstring);
        if(tempstring[0] == -1) break;
    }
    return strings;
}

Is there an easy way to check to see if the user has entered 'Ctrl-D'? 有没有一种简单的方法来检查用户是否输入了“ Ctrl-D”?

Never use scanf . 切勿使用scanf

If you have getline , use that. 如果您有getline ,请使用它。 Otherwise, use fgets . 否则,请使用fgets Either way, a typed Ctrl-D (or end-of-file from redirected input) will be passed up to you as zero characters read , ie an empty string. 无论哪种方式,键入的Ctrl-D(或来自重定向输入的文件结尾)都会作为零字符读取 (即空字符串)传递给您。 (If the user just presses Return without typing anything first, you get the one -character string "\\n".) (如果用户只按Return键而不先输入任何内容,则将获得一个-字符串“ \\ n”。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM