Jump to content

I want to write a program that can convert kg to g or g to kg. I just don't know how to have two options that the user can input in 1 run (ex: user wants to convert g to kg). Is there a function in stdio.h that allows me to do that?

 

Edit: How would I do the same thing for outputting the results?

Link to comment
https://linustechtips.com/topic/664271-c-code-help/
Share on other sites

Link to post
Share on other sites

https://en.wikibooks.org/wiki/C_Programming/Simple_input_and_output

 

#include "stdio.h"

int main(void) 
{
   int a;

   printf("Please input an integer value: ");
   scanf("%d", &a);
   printf("You entered: %d\n", a);

   return 0;
}

 

Link to comment
https://linustechtips.com/topic/664271-c-code-help/#findComment-8580780
Share on other sites

Link to post
Share on other sites

You can set scanf's format to "%d %2s" and arguments int and char [3].

user just enters eg. 20 kg and 20 goes to integer variable, and "kg" goes to cstring variable, in format there is %2s so up to only two characters will be applied to variable so it wont overflow the cstring, you would set length according to the longest unit name your program handles, it also automatically appends NULL char at the end of array, so your array has to be 1 character longer then format you accepting.

 

int i = 0;
char s[3];


printf("Enter quantity and unit you want to convert: ");
if(scanf("%d %2s", &i, &s) == 2){
	printf("You want to convert %d %s", i, s);
} else {
	printf("Entered data is invalid.");
}

You can see I compare result of scanf against 2, scanf returns number of arguments it managed to fill, so if all data was valid (there was number first and string later) it will return 2, if you enter string first, it will return 0 as such data doesn't match the format, and it won't be consumed, so you would need to consume it somehow if you want to keep asking for data until input will be valid. If you won't clear stdin then program will loop as invalid data won't be ever consumed.

Link to comment
https://linustechtips.com/topic/664271-c-code-help/#findComment-8583252
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×