2015-11-17 110 views
1

我试图调试一个程序,它是从标准输入中得到值'S'或'P'。我的功能calc_resistance()需要区分这两种情况,以及既没有输入'S'也没有输入'P'的情况。程序总是评估第三种情况(既不是'S'也不是'P'),为什么这样呢?比较从标准输入读取的字符输入

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 

float calc_resistance(char conn) { 

float retval = 0.0; 

if (conn == 'S') { 
    retval = 1; 
} 
else if (conn == 'P') { 
    retval = 2; 
} 
else { 
    retval = -1; 
} 
return retval; 
} 

int main() { 
    char connection_type[25]; 
    float resistance = 0.0; 

    while(1) { 
    printf("Enter 'S' or 'P': "); 
    scanf("%s", connection_type); 
    if(strlen(connection_type) != 1 || 
     (strncmp(connection_type,"S",25) && strncmp(connection_type,"P",25))) { 
     printf("Answer not understood. Enter 'S' or 'P'.\n"); 
     continue; 
    } 
    break; 
} 

    resistance = calc_resistance(connection_type); 

    printf("Connection type: %f", resistance); 

} 

回答

2

你正在做的这个错误是当它被定义为只接受单一char到一个数组传递给calc_resistance()功能。

眼看输入模式,connection_type并不需要是一个数组,%c格式说明符的帮助下,你可以很容易地connection_type一个char变量输入工作。

您可以通过scanf()man page了解更多。另外,在每次迭代之后,不要忘记清除剩余的换行

道德故事::启用编译器警告并注意它们。

0

你想检测前两个案件吗?如果是,那么尝试这一个,而不是在你的功能

calc_resistance(connection_type)
只传递一个字符,然后尝试传递整个地址,你可以修改代码如下。

 

    #include 
    #include 
    #include 

    float calc_resistance(char conn) 
    { 

      float retval = 0.0; 

      if (conn == 'S') 
      { 
        retval = 1; 
      } 
      else if (conn == 'P') 
      { 
        retval = 2; 
      } 
      else 
      { 
        retval = -1; 
      } 
      return retval; 
    } 

    int main() 
    { 
      char connection_type[25]; 
      float resistance = 0.0; 

      while(1) 
      { 
        printf("Enter 'S' or 'P': "); 
        scanf("%s", connection_type); 

        if (strlen(connection_type) != 1 || (strncmp(connection_type,"S",25) && strncmp(connection_type,"P",25))) 
        { 
          printf("Answer not understood. Enter 'S' or 'P'.\n"); 
          continue; 
        } 
        break; 
      } 

      resistance = calc_resistance(connection_type[0]); 

      printf("Connection type: %f", resistance); 

    }