0

我如何使用 scanf 读取带有空格的字符串(不输入)?而且我还希望这个程序在输入为 EOF 时停止

我使用了以下代码:

int main()      //this is not the whole program
{
    char A[10000];
    int length;

    while(scanf(" %[^\n]s",A)!=EOF);
    {
        length=strlen(A);
        print(length,A); 
        //printf("HELLO\n");
    }


    return 0;
}

但它正在读取两个 EOF(ctrl+Z) 来停止程序。任何人都可以给我任何建议吗?

4

1 回答 1

1

它正在读取两个 EOF(ctrl+Z) 以停止程序

不,您可能按两次 ^Z,但 scanf()只是“读取”一个 end-of-file EOF。这就是您的键盘/操作系统界面的工作方式。研究如何发出文件结束信号。

其他变化

char A[10000];
// while(scanf(" %[^\n]s",A)!=EOF);
// Drop final `;`  (That ends the while block)
// Add width limit
// Compare against the desired result, 1, not against one of the undesired results, EOF
// Drop the 's'
while(scanf(" %9999[^\n]", A) == 1) {
    length=strlen(A);
    // print(length,A); 
    print("%d <%s>\n", length, A); 
    //printf("HELLO\n");
}
于 2018-11-30T13:41:59.670 回答