2014-03-27 39 views
-1

我试图联合 所以,我不明白为什么我的编译器是不是让我接受输入时convhex()从主叫的原因。它直接打印一些结果..我不明白这一点。 下面的代码..为什么这个功能会给人意想不到的结果?

#include <stdio.h> 
#include <stdlib.h> 
#include <math.h> 
#include <String.h> 
void convhex(); 
void convert(int no, int base); 
int checkValid(int base,int no); 
// function prototyping done here 

void convhex() 
{ 
    char ch[10]; 
    int dec=0; 
    int i, res; 
    printf("Enter the hexadecimal number \n"); 
    scanf("%[^\n]", ch); 

    // print in decimal 
    for(i=strlen(ch)-1;i>=0;i--) 
    { 
     if(ch[i]>65) 
      res=ch[i]-65+10; 
     else 
      res=ch[i]-48; 
     //printf("%d", res); 
     dec=dec+pow(16,strlen(ch)-(i+1))*res; 
    } 
    printf("\nThe number in decimal is %d \n", dec); 
} 
int checkValid(int base,int no) 
{ 
    int rem; 
    //flag; 
// flag=0; 
    while(no>0) 
    { 
     rem=no%10; 
     if(rem>base) 
     { 
      //flag=1; 
      //break; 
      return 0; 
     } 
     no/=10; 
    } 
    return 1; 
    /* 
    if(flag==1) 
     printf("Invalid Input"); 
    else 
     printf("Valid Input"); 
     */ 
} 

void convert(int no, int base) 
{ 
    int temp, mod, sum=0, i=0; 
    temp=no; 
    while(temp>0) 
    { 
     mod=temp%10; 
      temp=temp/10; 
      sum=sum+pow(base,i)*mod; 
     i++; 
    } 
    printf("\n The number in base 10 is %d", sum); 
} 
int main() 
{ 
    int base, no; 
    printf("Enter the base \n"); 
    scanf("%d", &base); 
    if(base==16) 
     convhex(); 
    else 
    { 
     printf("Enter the number \n"); 
     scanf("%d", &no); 
     printf("You have entered %d", no); 
     if(checkValid(base, no)) 
     convert(no, base); 
    } 


    return 0; 
} 

// up until now our program can work with any base from 0-10 but not hexadecimal 
// in case of hex, we have A-F 
+0

你的编译器说什么? – HAL

+0

它在命令提示符下显示如下: http://puu.sh/7Lwa8.png – Xavier

+0

'scanf(“%[^ \ n]”,ch);' – BLUEPIXY

回答

0

scanfconvhex被读取由scanfmain离开\n
试试这个

scanf(" %[^\n]", ch); 
     ^An extra space will eat any number of white-spaces. 
+1

向下选民,评论,将不胜感激? – haccks

+0

'scanf'与正则表达式无关。 –

+0

@YvesDubois;我不这么认为。 – haccks

0

你可以从scanf删除%[^\n]connhex将其改为:

scanf("%s", ch) 

,或者你可以做什么haccks在上面的帖子建议。

+0

您可能想要解释*为什么*,但这种修复方法比使用'[^ ​​\ n]'更有意义。 – Mike

+0

'%'转换放弃了输入中的初始“空格” –

相关问题