【问题标题】:Request for an explanation of a program which uses the getchar() in a while statement请求解释在 while 语句中使用 getchar() 的程序
【发布时间】:2020-03-12 01:14:14
【问题描述】:

如果我祈求从第 7 行开始解释以下代码,问会不会太过分?在大多数情况下,我很难理解 getchar() 与 gets() 或 scanf() 的不同之处。为什么添加一个转义序列很重要, \n 在我的信念中,值输入将以水平形式完成(因为它是一维字符串)?递增然后立即使用递减运算符也让我感到困惑。此外,需要有关 strcpy() 的帮助。 :| 如果有人有时间,我恳求指导。谢谢!

main()
{
    char st[80], ch, word[15], lngst[15];
    int i, l, j;
    printf("\n Enter a sentence \n ");
    i = 0;
    while((st[i++] = getchar()) != '\n');
    i--;
    st[i] = '\0';
    l = strlen(st);
    i = 0; j = 0;
    strcpy(word," ");
    strcpy(lngst," ");
    while(i <= l)
    {
        ch = st[i];
        if(ch == ' ' || ch == '\0')
        {
            word[j] = '\0';
            if(strlen(word) > strlen(lngst))
            strcpy(lngst, word);
            strcpy(word," ");
            j = 0;
        }
        else
        {
            word[j] = ch;
            j++;
        }
        i++;
        }   
        printf("\n Longest word is %s", lngst);
        printf("\n Press any key to continue...");
        getch();
}

【问题讨论】:

  • 注:function:gets()已被贬值多年,并从最新版本的C标准中完全删除

标签: c while-loop strcpy getchar


【解决方案1】:
while((st[i++] = getchar()) != '\n');

效果和

一样
while (1) { // "infinite" loop
    int tmp = getchar(); // get keypress
    st[i] = tmp; // copy to string
    i++; // update index
    if (tmp == '\n') break; // exit the infinite loop after enter is processed
}

【讨论】:

    【解决方案2】:

    我不能说为什么要按原样编写代码(还有其他输入选项),但我可以解决您的一些担忧:

    为什么添加转义序列很重要,\n?

    当您按下return/enter 键时,getchar() 返回此“换行符”字符(典型的“信号”用于指示您已完成输入文本行)。如果不检查这一点,getchar 函数只会继续(尝试)读取更多字符。

    getchar() 与 get() 或 scanf() 有何不同?

    使用scanf 函数(this SO Q/A 可能有帮助)读取包含空格的文本是出了名的棘手,并且gets 函数已被声明为过时(因为它很危险)。一个可以使用fgets(st, 80, stdin),但就像我说的,我不能评论为什么代码写得一模一样。

    递减运算符的递增然后立即使用 也让我迷惑。

    表达式(st[i++] = getchar()) 将读取的字符传输到i 索引的st 数组元素中,之后 增加i 的值,因此下次调用getchar 会将其结果放入下一个数组元素中。但是,当\n(换行符)字符被读取时,i 将被递增,为 next 字符做好准备——但不会有一个,因此我们将其减少之后我们完成了while 循环。

    另外,需要有关 strcpy() 的帮助。

    调用strcpy(dst, src) 会将字符串src 中的所有字符(直到并包括必需 nul 终止符'\0')复制到dst 字符串,替换已经存在的任何内容。

    请随时要求进一步澄清和/或解释。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多