How can I get the same result, but entering the values by keyboard?

0
#include <stdio.h>

int main(){
 int primerNumero;
 int segundoNumero;
 int tercerNumero;
/*Cuando intento ingresar por ejemplo el valor del primer numero por teclado con scanf, luego me tira error si intento--> segundoNumero = 0primerNumero;*/
/*Quiero lograr hacer la conversión de la misma forma*/

/*ESTO ES LO QUE QUIERO INTENTAR CONSEGUIR
scanf("%d",&primerNumero);
segundoNumero = 0primerNumero;
tercerNumero = 0xprimerNumero;*/
 primerNumero = 15;
 segundoNumero = 015;
 tercerNumero = 0x15;
 printf("El primer numero es %d, ", primerNumero);
 printf("el segundo es %d, ", segundoNumero);
 printf("el tercer numero es %d.", tercerNumero);
 return 0;
}

Output:

El primer numero es 15, el segundo es 13, el tercer numero es 21.
    
asked by Jonathan Yañez 20.11.2017 в 15:14
source

1 answer

0

What you have to do is, first, read the data as a string. Why? Because once you have it in numerical format the base is lost (the computer internally works with a fixed base).

Once you have read the number as a string what you can do is use a function similar to scanf to interpret the number with different bases:

#include <string.h>

char buffer[10];
scanf("%s",buffer);

sscanf(buffer,"%d",&primerNumero);  // %d -> base 10
sscanf(buffer,"%o",&segundoNumero); // %o -> base 8
sscanf(buffer,"%x",&tercerNumero);  // %x -> base 16

sscanf works equal to scanf only that instead of recovering data% stdin process the buffer that is passed as the first parameter.

    
answered by 20.11.2017 / 15:55
source