我怎样才能使用scanf获得字符串呢?

时间:2018-11-30 12:52:29

标签: c string scanf

如何使用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)来停止程序。有人可以给我任何建议吗?

1 个答案:

答案 0 :(得分:1)

  

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

不。您可能按了两次^ Z,但是scanf()仅“读取”一个文件结尾EOF。这就是您的键盘/ OS界面的工作方式。研究如何用信号通知文件结束。

其他更改

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");
}