在C中幸存的回车/回车

时间:2015-12-30 23:31:38

标签: c newline scanf

# make test
cc     test.c   -o test
# ./test
I am a happy yam until i hit return...
# ./test
because it ends my [BLEEPING] program....
# ./test
OOOH  how my blood doth burn !!!  ...doth? ...doest? ...meh...
# cat test.c
#include "usual_suspects.h"

int main()
{
    int i;
    scanf( "%d", &i);
}
# echo 'So, how do I continue onto the next line
> without terminating the program? Not a wrapping function but,surviving
> hitting the enter key?

不是Dornishman的妻子,但嘿,我的预算低,半脑筋。的xD 扫描是写入的方式(看看我在那里做了什么)与它一起去?

UPDATE-根据答案a la hexturtle

# make test
cc     test.c   -o test
# ./test
Well blow me down, a cross-eyed clown !
Said a can of yams imported from Spain.
If i had a bucket to spit,       
I'd sorely say frak-it and quit !
Whilst watching my brine wash away
        with the rain. xD
^C
# YES !!!!!!!!!
bash: YES: command not found
# cat test.c
#include "usual_suspects.h"

int main()
{
    int i;
    while (true) {
        scanf("&d", &i);
    }
}

最终修改,承诺= D 好的,这就像我想的那样小。

#include "usual_suspects.h"
    int main()
    {
        while (true) {         
        scanf("%d");
        }
    }

2 个答案:

答案 0 :(得分:1)

当您致电scanf()时,程序将阻止,等待控制台输入。因此,一旦您按Enter键,您输入的输入将被读入,scanf()将返回。一旦scanf()返回,您的程序将继续执行。在您给出的示例中,scanf()返回后没有更多代码可以执行。因此,main()函数隐式返回0并导致程序退出。

如果您想继续阅读输入行,可以执行以下操作:

while (true) {
    scanf("%d", &i);
}

在实践中,有更好的方法可以做到这一点,正如Elliot Frisch所说。但原则上,这是我认为你正在尝试做的事情。

答案 1 :(得分:1)

fread()功能可以满足您的需求。它将读取指定的字节数或直到达到EOF,然后在unix上用CTRL + D输入到键盘。

#include <stdio.h>
#include <unistd.h>

#define MAX_STR_LEN 500

int main()
{
    // Declare a char array to read into
    char str[MAX_STR_LEN + 1];

    // Read into the char array until MAX_STR_LEN bytes
    // have been read or EOF
    fread(str, 1, MAX_STR_LEN, stdin);

    // Null Terminate and print what we read in
    str[MAX_STR_LEN] = '\0';
    printf("%s", str);
    fflush(stdout);
}

这个缺点是你没有得到花哨的scanf格式说明符。你必须自己处理大的结果串。

但要意识到这一点:在后台,fread()正在进行多个read()系统调用,这些调用在每个换行符后返回。因此,我认为从单行中获得的任何东西都可以获得新的成就。

在实践中,我已经找到了最佳解决方案,并且可以阅读过去的换行符&#34;是逐行读取文件。这可以通过下面更优雅的代码来完成,如果你真的需要连接的结果字符串,只需在字符串上使用strcat()

while (EOF != scanf("%s", &str)) {
   // Do something
}

但上面的代码可以满足您的要求。

相关问题