繁体   English   中英

如何解释用户输入的字符串?

[英]how to interpret the string entered by the user?

int main()
{
printf("Welcome to the temperature control program:\n");
    printf("enter the ascii temperature characters");
    printf("enter the ascii characters of an euipment name with + or - and followed by a integer value");
    printf("type character terminated by carriage return");

    char tbuffer [tbuffer_length];
    printf("enter the temperature value");
    scanf("%7c", tbuffer);
    char *t;
    t = fgets (tbuffer, tbuffer_length, stdin );
    if(tbuffer[0] = 'A')
    {

    }
    if (tbuffer[0] = 'B')
    {

    }
    if (tbuffer[0] = 'C')
    {

    }

return 0;
}

在这种情况下,用户输入字符串值(例如:char buffer [7] = {'A','+','2','5','。','5','\\ r'} )如何将此字符串解释为A具有设备A或B具有设备B,+ 25.5具有温度值(我想将此温度值转换为整数)和回车符。 解释并转换为整数后,我需要通过接口发送(我知道如何通过接口发送)。 给我一些解释的想法。

使用==运算符比较值

int main()
{
printf("Welcome to the temperature control program:\n");
    printf("enter the ascii temperature characters");
    printf("enter the ascii characters of an euipment name with + or - and followed by a integer value");
    printf("type character terminated by carriage return");

    char tbuffer [tbuffer_length];
    printf("enter the temperature value");
    scanf("%7c", tbuffer);
    char *t;
    t = fgets (tbuffer, tbuffer_length, stdin );
    if(tbuffer[0] == 'A')
    {

    }
    if (tbuffer[0] == 'B')
    {

    }
    if (tbuffer[0] == 'C')
    {

    }

return 0;
}

在您的代码中scanf("%7c", tbuffer); 应该是scanf("%7s", tbuffer);

同样, if(tbuffer[0] = 'A')应该是if(tbuffer[0] == 'A') 其他if语句也相同。

要将字符串转换为整数,请尝试以下代码,

char temp[10];
int dec,frac; 



if(tbuffer[0] = 'A')
{
   i=2;
   j=0;
   while(tbuffer[i] != '.')
   {
      temp[j]=tbuffer[i];
      j++;
      i++;
   }
   temp[j]='\0';
   dec=atoi(temp);
   j=0;
   i++;
   while(tbuffer[i] != '\0')
   {
      temp[j]=tbuffer[i];
      j++;
      i++;
   }   
   temp[j]='\0';
   frac=atoi(temp);
}

现在,变量dec包含小数部分,而frac包含小数部分。

例如,如果buffer[7]= {'A', '+', '2', '5', '.','5','\\0'}; 然后dec = 25frac = 5

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM