【问题标题】:Why cant I read function out the switch statement为什么我不能读出函数 switch 语句
【发布时间】:2012-10-04 14:14:18
【问题描述】:

程序将字符串存储为字符串数组。字符串可以是名称、地址等。 • 程序显示一个选择屏幕,允许用户输入字符串(最多 16 个,字符串有一个 最多 128 个字符),从数据库中删除一个字符串,查看数据库中的字符串,搜索一个 字符串,然后退出程序。

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
void clearscreen()
{
    system("cls");
}

int main()
{
    int b1,b,c;
    char data[20]; 
    int number,a;

    do{
        clearscreen();
        printf("How many data do you want to store  ");
        scanf("%d",&number);

        for(a=1;a<=number;a++)
        {
            printf("Input your data %d_No:       ",a);
            scanf("%s",&data[a]);
        }

        printf("What action do you want to do\n [1]Remove data\n [2]View data\n [3]Search data\n[4] Quit");
        scanf("%d",&b1);

        switch(b1)
        {
            case 1:

                clearscreen();
                break;
            case 2:
                for(c=1;c=number;c++)
                {
                    printf("%d:%s",a,data[a]);
                }
                break;
            case 3:
                break;
            case 4:
                return 0;
                break;
        }

        printf("\nDO you want to continue\n[1] YES\n [2] No   ");
        scanf("%d",&b);
        if (b==2)
        {
            return 0;
        }
    } while(b !=2);
}

程序正在运行,但是当我切换到 2 时,它无法读取 int 数和 char 数据 为什么?我该怎么办?

【问题讨论】:

  • 您应该更好地格式化您的代码,在您的编译器中启用所有警告和调试信息,尝试编写符合标准的代码(注意&lt;conio.h&gt; 不是标准的),并学习如何使用您的调试器,然后逐步使用它。
  • 您预计会发生什么?怎么了? - 案例 2 中的 for 循环看起来很奇怪:for(c=1; c=number; c++) - 应该是

标签: c


【解决方案1】:
for(c=1;c=number;c++)
    printf("%d:%s",a,data[a]);

我在这里看到三个问题。首先,根据您的数据输入循环,您可能指的是c &lt;= number

第二个是您使用a 作为数组索引,而不是您应该使用的c

最后是数组是从零开始的,所以int a[20] 给你a[0]a[19] 包括在内。换句话说,你的循环应该从0number - 1 而不是1number

【讨论】:

    【解决方案2】:

    在情况 2 中使用 c 变量并使用 c&lt;=number 而不是 c=number

    for(c=1;c<=number;c++)
                    {
                        printf("%d:%s",c,data[c]);
                    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-09-25
      • 1970-01-01
      • 2011-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多