一次复制和粘贴多行输入时 scanf 挂起

scanf hangs when copy and paste many line of inputs at a time

这可能是一个简单的问题,但我是 C 的新手,但找不到任何答案。我的程序很简单,它在一个 for 循环中输入 21 行字符串,然后打印出来。数量可能更少或更多。

int t = 21;
char *lines[t];
for (i = 0; i < t; i++) {
    lines[i] = malloc(100);
    scanf("%s", lines[i]);
}
for (int i = 0; i < t; i++) {
    printf("%s\n", lines[i]);
    free(lines[i]);
}
...

因此,当我一次复制和粘贴输入时,我的程序挂起,没有错误,也没有崩溃。如果只有 20 行或以下就可以了。如果我逐行手动输入,无论输入多少,它都能正常工作。

我在 Mac OS X 10.10 中使用 XCode 5,但我认为这不是问题所在。

更新:

我试图在程序挂起时调试它,当 i == 20 在下面一行时它停止了: 0x7fff9209430a: jae 0x7fff92094314 ; __read_nocancel + 20

这个问题可能与scanf有关,但是很困惑,为什么是数字20?可能是我用错了,非常感谢任何帮助。

更新:

我尝试使用 CLI gcc 编译程序。它工作得很好。所以,最终还是XCode的问题。它以某种方式阻止用户粘贴多个输入。

当您想在 C 中读取字符串时使用 fgets,并查看有关该函数的文档:

[FGETS Function]

所以你应该这样使用它:

fgets (lines[i],100,stdin);

所以它会从用户的输入中获取字符串,你可以看看这两个帖子以及关于在 C:

中读取字符串的内容

Post1

Post2

我希望这能帮助您解决问题。

编辑:

#include <stdio.h>
void main(){
int t = 21;
int i;
char *lines[t];
for (i = 0; i < t; i++) {
    lines[i] = malloc(100);
    fgets(lines[i],255,stdin);
}
for (i = 0; i < t; i++) {
    printf("String %d : %s\n",i, lines[i]);
    free(lines[i]);
}
}

此代码给出:

如你所见,我得到了我输入的 21 个字符串(从 0 到 20,这就是为什么它在 i==20 时停止)。

我尝试了你的输入,结果如下:

我写了和运行一样的代码。有用。 每行可能包含超过 99 个字符(包括换行符)... 或者它可能包含空格和制表符。

scanf(3)

When one or more whitespace characters (space, horizontal tab \t, vertical tab \v, form feed \f, carriage return \r, newline or linefeed \n) occur in the format string, input data up to the first non-whitespace character is read, or until no more data remains. If no whitespace characters are found in the input data, the scanning is complete, and the function returns.

要避免这种情况,请尝试

scanf ("%[^\n]%*c", lines[i]);

整个代码为:

#include <stdio.h>

int main() {

    const int T = 5;
    char lines[T][100];  // length: 99 (null terminated string)
    // if the length per line is fixed, you don't need to use malloc.
    printf("input -------\n");
    for (int i = 0; i < T; i++) {
        scanf ("%[^\n]%*c", lines[i]);
    }
    printf("result -------\n");
    for (int i = 0; i < T; i++) {
        printf("%s\n", lines[i]);
    }

    return 0;
}

如果问题仍然存在,请向我们展示输入数据和更多详细信息。最好的问候。