2016-09-15 202 views
0

处理此作业。不知道如何摆脱while循环,我不能使用比while循环更先进的任何东西。我尝试将int转换为char,但没有奏效。以下是我的代码。任何帮助,将不胜感激。如何在用户输入字母“q”时退出while循环 - C编程

/* This program has the user input a number. This number is then printed out in degrees F, C and K*/ 

#include <stdio.h> 

#define KEL 273.16 
#define CEL1 32 
#define CEL2 0.5555 

void temperatures(double temp); 


int main(void) 
{ 
    double tempF; // Temperature the user inputs 

    char userinput; // Quit character the user inputs 

    userinput = 'a'; 

    tempF = 0; 

    printf("Enter a temperature in degrees Farenheit or enter q to quit:\n"); 
    scanf_s("%lf", &tempF); 
    //scanf_s("%c", &userinput); 

    while ((char)tempF != 'q') 
    { 
     temperatures(tempF); 
     printf("Enter a temperature in degrees Farenheit or enter q to quit:\n"); 
     scanf_s("%lf", &tempF); 
     //scanf_s("%c", &userinput); 

    } 

    printf("Goodbye!\n"); 


    return 0; 
} 

void temperatures(double temp) 
{ 
    double celsius; 
    double kelvins; 

    celsius = (temp - CEL1) * CEL2; 
    kelvins = celsius + KEL; 

    printf("%lf F is %lf degrees C or %lf degrees K.\n", temp, celsius, kelvins); 


} 

回答

4

您需要更改策略。

  1. 阅读一行文字。
  2. 如果该行的第一个字母是q,则退出。
  3. 否则,尝试使用sscanf从行中读取数字。

下面是main的一个版本。

int main(void) 
{ 
    double tempF; // Temperature the user inputs 
    char line[200]; 

    while (1) 
    { 
     printf("Enter a temperature in degrees Fahrenheit or enter q to quit:\n"); 

     // Read a line of text. 
     if (fgets(line, sizeof(line), stdin) == NULL) 
     { 
     break; 
     } 

     if (line[0] == 'q') 
     { 
     break; 
     } 

     if (sscanf(line, "%lf", &tempF) == 1) 
     { 
     // Got the temperature 
     // Use it. 
     } 
     else 
     { 
     // The line does not have a number 
     // Deal with the error. 
     } 
    } 

    printf("Goodbye!\n"); 

    return 0; 
} 
1

你应该阅读输入作为字符串(scanning a string),并将其转换(atof),比使用strcmp到输入字符串与exit命令进行比较。 您还可以使用isdigit检查您输入(不要尝试任何不是一个数转换)

0

您可以

char c; 
while (c != 'q') { 
    scanf("%c", &c); 
    //parse command 
} 
读取字符