【问题标题】:while (scanf()==1) doesn't work - what is my mistake?而 (scanf()==1) 不起作用-我的错误是什么?
【发布时间】:2015-08-28 11:24:51
【问题描述】:

以下是同一程序的两个版本。第一个有效,第二个无效。使用while (scanf()==1) 我想检查scanf。请解释一下我的错误是什么(请简单地说-我是初学者:))

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

int main (void)
{
    char string_to_cap[90];
    int i, n;

    // get line of text
    printf ("Please, enter a word: ");
    scanf  ("%89s", string_to_cap);

    if (string_to_cap != NULL) // if s is not NULL than go ahead and execute the code below

    {
        // capitalize text
        for (i = 0, n = strlen(string_to_cap); i < n; i++)
        {
            printf("%c", toupper(string_to_cap[i]));
        }
    }
    printf ("\n");
}

这是第二个不起作用的:

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

int main (void)
{
    char string_to_cap[90];
    int i, n;

    // get line of text
    printf ("Please, enter a word: ");

    while (scanf  ("%89s", string_to_cap) == 1);

    {
        // capitalize text
        for (i = 0, n = strlen(string_to_cap); i < n; i++)
        {
            printf("%c", toupper(string_to_cap[i]));
        }
    }
    printf ("\n");
}

【问题讨论】:

  • 也许删除 while (scanf() ==1) 之后的分号? ;-)
  • 在你的第一个例子中:string_to_cap 永远 (!) NULL
  • 稍后删除分号。使用这种编码方法,您的条件永远不会错误。
  • string_to_cap 怎么可能是NULL
  • while 循环有分号,如果这是您的要求,那么只需在输入后输入 ctrl+z。然后它会工作。

标签: c scanf


【解决方案1】:
while (scanf  ("%89s", string_to_cap) == 1);
                                           ^

注意错误

这实际上意味着while循环只有一个语句,即;

以及之后的块

{
    // capitalize text
    for (i = 0, n = strlen(string_to_cap); i < n; i++)
    {
        printf("%c", toupper(string_to_cap[i]));
    }
}

永远不会被执行。

【讨论】:

  • 谢谢大家!我希望以后能避免这样的错误。
  • 我已经删除了该列(确实,有趣的错误),但现在程序甚至无法编译。我收到错误消息:Undefined symbols for architecture x86_64: "_main", referenced from: start in crt1.10.6.o ld: symbol(s) not found for architecture x86_64 collect2: ld returned 1 exit status
  • 另外,我的while语句不是意味着一个无限循环,如果完全解决了任务,成功输出后不会退出?我应该为 if 语句更改它吗?虽然我仍然必须先解决上述问题。
  • @Ducol 删除了该列?是的,您需要更改为if 声明。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-10-06
  • 1970-01-01
  • 2020-06-25
  • 1970-01-01
  • 2015-02-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多