【问题标题】:Garbage values assigned while using dynamic input; in C language使用动态输入时分配的垃圾值;在 C 语言中
【发布时间】:2015-03-17 15:34:56
【问题描述】:

问题是,在输出中,属性 sp、bp、temp、cold、fever 和胃被分配了垃圾值,而且为 symp[i] 输入的字符串没有正确存储。 这不是一个完整的程序,它还有一些额外的工作要做。

程序如下..头文件为stdio.h和conio.h

#include<stdio.h>
#include<conio.h>
void main()
{    
 char * symp[10];
 int n=0,i,sp,dp,cold,fever,stomach;    
 float temp;   
 clrscr();
 printf("Enter your body temperature: ");    
 scanf("%f",&temp);    
 printf("Enter your systolic BP: ");    
 scanf("%d",&sp);    
 printf("Enter your diastolic BP: ");    
 scanf("%d",&dp);    
 printf("Enter the no of symptoms: ");    
 scanf("%d",&n);    
 printf("Enter the symptoms you have, one by one\n");
 fever=cold=stomach=0;    
 for(i=0;i<n;i++)    
 {    
  scanf("%s",symp[i]);    
  printf("i=%d\tn=%d\n",i,n);    
  if(symp[i]=="cough")    
  { cold=cold+1;}    
  if(symp[i]=="sneezing")    
  { cold=cold+1;}    
  if(symp[i]=="running_nose")    
  { cold=cold+1;}   
  if(symp[i]=="headache")    
  { cold=cold+1;fever=fever+1;}    
  if(symp[i]=="chill")    
  { fever=fever+1;  }  
  if(symp[i]=="weakness")    
  { fever=fever+1; }   
  if(symp[i]=="stomach_pain")
  { stomach=stomach+1; }   
  if(symp[i]=="diarrhoea")
  { stomach=stomach+1;}    
  if(symp[i]=="vomiting")    
  { stomach=stomach+1;fever=fever+1;}
  if(symp[i]=="throat_pain")   
  { cold=cold+1;}    
  if(symp[i]=="body_pain")
  { fever=fever+1;}
 }
printf("Your temperature is: %f\n",temp);
printf("Your BP is: %d/%d\n",sp,dp);
printf("The symptoms are:\n");
for(i=0;i<n;i++)
 {
 printf("%s\n",symp[i]);
 }
printf("cold: %d\nfever: %d\nstomach: %d",cold,fever,stomach);
getch();
}

【问题讨论】:

  • 请缩进并删除空行。没有人喜欢滚动。
  • 你必须检查scanf()返回值,你不能抱怨垃圾值,因为你的代码不安全,因为它没有错误检查。
  • 您的某些if 条件缺少大括号{}
  • @user694733 你有鹰眼,在这乱七八糟的情况下你怎么能注意到这一点?
  • 你想用if(symp[i]=="cough")做什么?

标签: c


【解决方案1】:

您不能将char[] 与带有== 的静态字符串进行比较,您必须使用strcmpstrncmp,例如:

 if (strcmp(symp[i], "headache"))

您还必须将 地址 传递给 scanf("%s", ...),例如:

scanf("%s", &symp[i]);

【讨论】:

    【解决方案2】:

    您正在 scanf() 发送字符串并将 char * 传递给 scanf() 而不对其进行初始化

    scanf("%s", symp[i]);
    

    这是错误的。

    你需要为正确存储的字符串分配空间,所以你可以尝试这样做

    char symp[100][10];
    

    然后你的scanf() 看起来像这样

    scanf("%99s", symp[i]);
    /*      ^ this prevents overflowing `symp[i]' */
    

    然后,正如@PaulEvans 提到的其他answer 所提到的,您需要使用strcmp() 来比较字符串。

    【讨论】:

      猜你喜欢
      • 2020-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-20
      • 2017-10-12
      • 1970-01-01
      • 2018-08-22
      • 2016-06-11
      相关资源
      最近更新 更多