[英]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 = 25
而frac = 5
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.