【问题标题】:why are my scanf statements not working?为什么我的 scanf 语句不起作用?
【发布时间】:2015-07-22 09:12:59
【问题描述】:

我是一个初学者,但我已经在这个代码上工作了一周,我无法让我的 scanf 函数工作。我所有的printf 函数输出都很好,但是如果我输入我的信息来测试我的代码,我什么也得不到。我在这里错过了一些简单的东西吗?

#include <stdio.h>
float average(float a[]);
int main ()
{
    /* variable definition: */
    char personsName[100];
    char personsAge[3];
    char personsState[20];
    float Age, Texas;
    int people,age,i,count,Avg,None;
    // Loop through 50 people
    for (people=0; people <2 ; people++)
    {

        Age =0.0;
        printf("Enter Persons Name \n");
        scanf("%s", personsName);
        printf("Enter None if this is last family member. \n");
        scanf("%s", personsName);
        {
            if (personsName == None)
                break;
        }
    }
    {
        printf("Enter Persons Age \n");
        scanf("%s", personsAge);
        float average(float a[])
        {
            printf("Average of all family members is %f \n");
            int i;
            float avg, sum=0.0;
            for(i=0;i<50;++i)
                sum+=a[i];
            avg =(sum/i);

            return avg;
        }
    }
    {
        printf("Enter Persons State \n");
        scanf("%s", personsState);
        while (Texas > 0)
        {
            printf("Enter Texas\n");
            scanf("%f",&Texas);
            //Only assign if positive
            if (Texas > 0)
            {
                personsState[count]=Texas;
                count = count + 1;
                break;
            }
        }
    }
    // Print data
    for (i=0; i<count;i++)
    {
        printf ("Texas %f is %d\n", i,personsState[i]);
        if (count == 50)
            break;
    }

    return 0;
}

【问题讨论】:

  • 你真的有嵌套函数还是带有缩进的东西?
  • 您将字符串(指针)与整数而不是“无”文字进行比较
  • @SouravGhosh:它不是嵌套函数,但在for 之后有两个独立作用域,这可能不是 OP 想要的。
  • @MOehm 我说的是average()函数。
  • @SouravGhosh:好的,错过了。 (不过,隐藏它的好地方。格式和程序逻辑一团糟。)

标签: c scanf


【解决方案1】:

问题,正如我所看到的那样

if (personsName == None)

这不是比较两个字符串的方法。您需要使用strcmp() 来比较内容。

另外,两个连续的scanf()s 具有相同的参数来存储输入。第二个scanf() 将覆盖之前的输入。

FWIW,但是,None 不是 字符串。您需要使用"None" 来表示一个字符串。

也就是说,通过scanf() 的不受控制的输入会导致缓冲区溢出。最好使用长度说明符限制您的扫描,例如

 scanf("%99s", personsName);

等等。

【讨论】:

    猜你喜欢
    • 2011-07-16
    • 2012-07-21
    • 1970-01-01
    • 1970-01-01
    • 2011-12-20
    • 2013-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多