在 C 中幸存 Enter/carriage return

Surviving Enter/carriage return in C

# 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 scanf 是用于此的写入方式(看看我在那里做了什么)吗?

更新-根据答案 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");
        }
    }

当您调用 scanf() 时,程序将阻塞,等待控制台输入。因此,一旦您按下回车键,您提交的输入将被读入并且 scanf() 将 return。一旦 scanf() returns,你的程序就会继续执行。在你给出的例子中,在 scanf() returns 之后没有更多的代码要执行。因此,main() 函数隐式 returns 0 并导致程序退出。

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

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

实际上,正如 Elliot Frisch 提到的那样,有更好的方法可以做到这一点。但原则上,这就是我认为你正在尝试做的事情。

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] = '[=10=]';
    printf("%s", str);
    fflush(stdout);
}

这个缺点是您没有花哨的 scanf 格式说明符。你只需要自己处理大的结果字符串。

但要意识到这一点:在后台,fread() 正在进行多个 read() 系统调用,每个换行符后 return。所以我认为在换行后仍然存在的单个函数没有任何好处。

在实践中,我发现 "read past newlines" 的最佳解决方案是读取文件 line-by-line。这可以通过下面更优雅的代码来完成,如果您确实需要连接结果字符串,只需在字符串出现时使用 strcat()

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

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