gpt4 book ai didi

c - 在 C 中检测新行

转载 作者:太空宇宙 更新时间:2023-11-04 06:54:44 25 4
gpt4 key购买 nike

我的代码是这样的:

char k[1000];
while(1){
scanf("%s",&k);
if(k[0] == '\n'){
exit(0);}
/* Do some processing on k */
memset(k,0,1000);
}

我的意图是按正常方式处理用户输入,并在用户输入空字符串或换行时终止。这似乎不起作用。

你们能帮我看看哪里出了问题吗?

相关说明,如果是文件末尾我也想终止,对于EoF我应该怎么做?

预先感谢您提供的所有帮助。

最佳答案

首先——不要使用scanf 进行用户输入。这是一个微妙问题的雷区,正等着咬新 C 程序员,而不是使用像 fgets 或 POSIX getline 这样的 line-oriented 输入函数。每次都读取(并包括)尾随的 '\n' (只要您为 fgets 提供足够大小的缓冲区 - 否则它只会继续阅读其缓冲区大小的字符 block ,直到遇到 '\n'EOF)

因此,要读取用户输入直到遇到空字符串EOF,您可以简单地执行如下操作:

#include <stdio.h>
#include <string.h>

#define MAXC 1000

int main (void) {

char k[MAXC] = "";

for (;;) { /* loop until empty-string of EOF */
printf ("input: "); /* prompt for input */
if (fgets (k, MAXC, stdin)) { /* read line (MAXC chars max) */
if (*k == '\n') { /* test for empty-string */
fprintf (stderr, "empty-string! bye.\n");
break;
}
size_t l = strlen (k); /* get length of string */
if (l && k[l - 1] == '\n') /* check if last char is '\n' */
k[--l] = 0; /* overwrite with nul-terminator */
printf ("got input: %s\n", k);
}
else { /* got EOF */
fprintf (stderr, "EOF -- bye.\n");
break;
}
}

return 0;
}

示例使用/输出

>bin\fgets_user_input.exe
input: this
got input: this
input: is some
got input: is some
input: input
got input: input
input:
empty-string! bye.

>bin\fgets_user_input.exe
input: this is more
got input: this is more
input: ^Z
EOF -- bye.

>bin\fgets_user_input_cl.exe
input: it works the same
got input: it works the same
input: compiled by gcc
got input: compiled by gcc
input: or by cl.exe (VS)
got input: or by cl.exe (VS)
input:
empty-string! bye.

(注意:对于 Linux Ctrl+d 生成 EOF,我刚好在上面的 windoze 上)

关于c - 在 C 中检测新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46598518/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com