C: Need help extracting values from strings [closed] - c

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am trying to get a duration of time into minutes from a string. I am given a string like this: "1:50". And I need to extract the minutes and seconds from this strings into int variables and then return the duration in minutes. So I wrote this:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <conio.h>
#include <string.h>
int main()
{
char time[6]="01:30";
int duration=0, minutes=0, seconds=0;
int buffermin[3];
int buffersec[3];
int i=0;
while(i<2)
{
sscanf(time[i],"%d%d",&buffermin[i]); //Get the first two characters in the string and store them in a intger array
i++;
}
i=3;
while(i<5)
{
sscanf(time[i],"%d%d",&buffersec[i]); //Get the last two characters in the string and store them in a integer array
i++;
}
printf("%d %d %d %d", buffermin[0], buffermin[1], buffersec[0], buffersec[1]);
getch();
minutes=(buffermin[0]*10)+buffermin[1]; //Put values in array to one variable
seconds=(buffersec[0]*10)+buffersec[1]; //Same as above
seconds=seconds/60; //Turn the number of seconds to minutes
duration=seconds+minutes; //Get total duration
printf("The total duration is: %d\n",duration); //Output total duration
getch();
exit(0);
}
Why is this not working and how could I fix this. Any examples would be really very appreciated. If you have the time to explain how the example works, please do so. Still poor at programming as you can see.

You should really learn how to use sscanf properly. Basically, what you want to achieve is this:
#include <stdio.h>
int main() {
char time[] = "01:27";
int minutes;
int seconds;
// Must be double, not integer, otherwise decimal digits will be truncated
double duration;
// String has format "integer:integer"
int parsed = sscanf(time, "%d:%d", &minutes, &seconds);
// Check if input was valid
if (parsed < 2) {
// String had wrong format, less than 2 integers parsed
printf("Error: bad time format");
return 1;
}
// Convert to minutes (mind the floating point division)
duration = (seconds / 60.0) + minutes;
printf("Duration: %.2f minutes\n", duration);
return 0;
}

Related

Why does my program not allow me a second input? [duplicate]

This question already has answers here:
Why you mustn't write scanf("%.2lf", &a) in C?
(2 answers)
Closed 4 years ago.
Suppose savings and expenses are variables of type double that have been given values. Write an if-else statement that outputs the word Solvent, decreases the value of Savings by the value of expenses and sets the value of expenses to 0, provided that savings is more than expenses. If however, savings is less than expenses, the if-else statement simply outputs the word Bankrupt and does not change the value of any variable.
Specific question: Why does my program skip immediately through after I type in a value for savings? How can I remedy it?
#include <stdio.h>
void solvent();
int main(void)
{
double savings, expenses;
printf("\nEnter a number for savings: ");
scanf("%2lf", &savings);
printf("Enter a number for expenses: ");
scanf("%2lf", &expenses);
if(savings > expenses)
solvent();
else
printf("Bankrupt!");
system("pause");
return 0;
}
void solvent(double savings, double expenses)
{
printf("Solvent!");
savings -= expenses;
expenses = 0;
}
Okay, for reasons I don't quite understand, making %2lf be just %lf was sufficient to fix this. Thanks to Weather Vane.

Bug in simple C source code? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I want to know if the format of user defined function i wrote i.e return(xxx) is correct or not .
Because when i compile my code, i have to enter the input 2 times.It might be a silly mistake because i just began learning C language
****MY CODE:****``
#include<stdio.h>
long cube(long x );
long input,answer;
int main (void )
{
printf("Enter a number:");
scanf("%ld ",&input);
answer = cube(input);
printf(" The cube of %ld is %ld",input ,answer);
return 0;
}
long cube(long x )
{
return (x*x*x);
}
****ANswer****
#include <stdio.h>
long cube(long x);
long input, answer;
int main( void )
{
printf("Enter an integer value: ");
scanf("%d", &input);
answer = cube(input);
printf("\nThe cube of %ld is %ld.\n", input, answer);
return 0;
}
long cube(long x)
{
long x_cubed;
x_cubed = x * x * x;
return x_cubed;
}
remove the space after '%ld' it will take one input.
according your code,
scanf("%ld '&input) ;
here compiler at first wants one input for '%ld' then it waits for blank space you used after '%ld'. remove it then it will go next step after one input.
you should use,
scanf("%ld%",&input);

Addition of two numbers in c [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
Is there any possibilities to read and add two or three different integers by using single variable ( int a ) in C language?
I didn't want to use array
I'm not sure I'm getting you, but for example, if you want to add 2 16 bits integers with a single 32bit integer, you could do
#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>
int main()
{
uint32_t a;
printf("Enter number 1: ");
scanf("%hd", (uint16_t *)(&a));
printf("Enter number 2: ");
scanf("%hd", ((uint16_t *)(&a))+1);
printf("%X\n", a);
printf("Sum = %"PRIu32"\n", (uint32_t)(*(uint16_t *)(&a)) + *(((uint16_t *)(&a)) + 1));
return 0;
}
The logic is to think about variable equals to arrays of bytes, and that's it.
This implementation still have problems that are well explained HERE
No. Every time you you atribute a new value to the same variable it replaces the old one. If you don't want to use an array and it's a simple code to add numbers, just declare three variables and atribute each value to one of them.
I do not know if you would like this, but another way you can do this will be to accept inputs like you punch in calculators, and parse to int before applying the operations on them.
Something like this
#include <stdio.h>
#include <string.h>
int main ()
{
char buffer[256];
char * pch;
printf("input your numbers in this format ${number1}+${number2}...: ");
fgets (buffer, 256, stdin);
int sum = 0;
pch = strtok (buffer, "+");
while (pch != NULL)
{
sum += atoi (pch);
pch = strtok (NULL, "+");
}
printf("the sum is %\n", sum);
return 0;
}
so, run it and input 2+2+2 and it does the calculation for you. thanks

Guess the number [duplicate]

This question already has answers here:
Why do I always get the same sequence of random numbers with rand()?
(12 answers)
Closed 9 years ago.
I have written a program but it always gives the same number (41).
Why does not it change next time I play?
Second question is: How can I limit the answer between 2 numbers?
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
int magic,guess;
char ans='y';
magic=rand();
printf("\t\t\tgame(guess the number)\n");
do{
printf("guess the magic number\n");
scanf("%d",&guess);
if(guess==magic){
printf("\n*****Right*****\n");
printf("%d is the magic number.",magic);
getch();
ans='n';
}else{
printf("\n*****Wrong*****\n");
if(guess>magic)
printf("your guess is too high\n");
else printf("your guess is too low\n");
printf("do you want to continue?\n");
ans=getch();
}
}while(ans=='y');
return 0;
}
I want to limit answer between 50 and 500. How can I do that?
put srand (time(NULL)); as the very first line of your main() function and let the magic start :)
now .... rand() gives you number in the range 0 to RAND_MAX
so lets say you want to limit it between x and y(inclusive)(x < y)
then int rand_num = rand() %(y-x+1) + x; would be your solution
Cheers :)
Seed the random number generator with srand - http://www.cplusplus.com/reference/cstdlib/srand/
Use something like the process ID and/Or the current time

Could anyone please help me with this c program coding? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
i have got a program to do as my homework. the program is simple. it asks to reverse the digits entered by the user and then print it using while loop. the problem arises when the user enters a number starting with zeroes.
For example:
Enter the number: 0089
The reversed number is : 9800
This is how the output should be. instead i get "98" as the answer.
and thanks in advance.
When asked to do someone else's homework, I like to devise an obtuse and compact way to do it.
void reverseNumber(void)
{
char c;
((c=getchar()) == '\n')? 0 : reverseNumber(), putchar(c);
}
Rather than reading the 0089 input as a numeric value, read it as a character array. This way the zeros won't be removed.
Read the numbers as a string.
And then use atoi() (stdlib.h) to make an integer number out if the string:
/* int atoi (const char *) */
Here is working code that makes exactly what your question requires:
// input: 0321
// output: 1230
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char str[80] = {0}, temp_str[80] = {0};
int num, i, length = 0, temp_length = 0;
printf("Enter a reversed number (e.g. 0089): ");
scanf("%s", str);
length = strlen(str);
temp_length = length;
printf("string_length: %d\n", length);
for ( i = 0; i < length; i++ ) {
temp_str[i] = str[temp_length - 1];
/* The string length is 4 but arrays are [0][1][2][3] (you see?),
so we need to decrement `temp_length` (minus 1) */
temp_length--;
}
printf("temp_str: %s\n", temp_str);
num = atoi(temp_str);
printf("num: %d\n", num);
return 0;
}

Resources