How to take input in hh:mm format in C++ and parse it?

  • Thread starter shivajikobardan
  • Start date
  • Tags
    C++ Input
In summary: Enter the day of the week: Su Mo Tu We Th Fr Sa"); let time_call_started = prompt("Enter the time the call started in the format 14:30"); const [hour, minute] = time_call_started.split(':'); let time_call_started_in_minutes = hour * 60 + minute; let length_of_call = prompt("Enter the length of call in minutes"); let cost_of_call; day_of_the_week_uppercase = day_of_the_week.toU
  • #1
shivajikobardan
674
54
Post moved from the technical computing forum to the schoolwork forums.
TL;DR Summary: hh:mm format input

1687097889251.png

I'm solving this problem.
I've the algorithm ready.

Here's it.
1687098031285.png

But it's the easy part. The hard part is to code it specially in C++. (Not that I can do this in javascript).
How do I take say 14:30 as input(exactly that) and parse 14, parse 30 from it?
 
Physics news on Phys.org
  • #2
This is a very trivial problem. How much experience do you have in programming? Have you dealt with strings at all?
 
  • #3
phinds said:
This is a very trivial problem. How much experience do you have in programming? Have you dealt with strings at all?
Is it trivial? I'm ashamed to tell how long I've experience in programming now.
 
  • #4
So, answer the question. Have you dealt with strings at all?
 
  • #5
phinds said:
So, answer the question. Have you dealt with strings at all?
yes I've but I don't know how to solve this problem.
 
  • #6
shivajikobardan said:
yes I've but I don't know how to solve this problem.
Do you know how to find the index in the string of the ":" character?

Alternately, I think there are functions that give the individual parts of the time value. I haven't programmed in C or C++ for decades and I don't remember for sure.
 
  • #7
Code:
#include <iostream>
#include <string>

int main()
{
    std::string time = "14:30";
    std::cout << food.find(":"); //output 2
}
 
  • #8
(Post edited by mentor)
The very first thing you should have done is to look at the std::string documentation. Not only will it list the methods you can use, it will even list examples.

While I do not recommend mixing C-like style with STL-like style, you also could have cracked open K&R and there at the very beginning it discusses scanf and where it is detailed in the book. Reading the documentation would have been a good start if you wanted to do it this way.
 
Last edited by a moderator:
  • Like
Likes phinds
  • #9
OK, now that this has been moved to homework help, please show your attempt.
 
  • Like
Likes berkeman and Bystander
  • #10
As a PS, I am surprised that your compiler does not throw at least a warning for using "time" as a variable name. That is like using "printf" as a variable name.

Even if allowed, it is a very very bad idea. And even if it weren't a very very bad idea it would still be a bad idea. A variable name should describe the varianble, not the variable type. You wouldn't call a string "aString" would you?
 
  • Like
Likes phinds
  • #11
Vanadium 50 said:
OK, now that this has been moved to homework help, please show your attempt.

Post #7, before your post above, has a very minimal attempt.

shivajikobardan said:
C++:
int main() 
{ 
    std::string time = "14:30";
    std::cout << food.find(":"); //output 2
}
food?
This won't compile.
The compiler won't complain about the time variable, but there is a C standard library header called time.h, that contains a number of functions and other stuff for dealing with time. The C++ version of this header is ctime. I don't think including this header will help much for this problem. Instead, it is more about parsing a string containing the call start time, and the logic to determine the cost of the call based on when the call starts and the length of the call.

In any case, time is not a very good name for a variable. Better would be callStartTime or something similar.
 
Last edited:
  • #12
I rely a lot on PF for programming because I'm not good at it. I've observed this as well. When I am trying to learn some subjects like computer networking, I'm not that much confused like I'm in programming. And yeah it's not helping me that much, but I guess I've to find a way to learn.
 
  • #13
@pbuk is right here, c++ is pain. i'm solving these exercises with javascript. the amount of methods available in javascript is ridiculous, so that you can just focus on programming.
 
  • #14
Code:
function costcalculator() {
  let day_of_the_week = prompt("Enter the day of the week: Su Mo Tu We Th Fr Sa");
  let time_call_started = prompt("Enter the time the call started in the format 14:30");
  const [hour, minute] = time_call_started.split(':');
  let time_call_started_in_minutes = hour * 60 + minute;
  let length_of_call = prompt("Enter the length of call in minutes");
  let cost_of_call;
  day_of_the_week_uppercase = day_of_the_week.toUpperCase();
  if (day_of_the_week_uppercase = "MO" || "TU" || "WE" || "TH" || "FR") {
    if (time_call_started_in_minutes >= 480 && time_call_started_in_minutes <= 1080) {
      cost_of_call = 0.40 * length_of_call;
    }
    else {
      cost_of_call = 0.25 * length_of_call;
    }
  }
  else {
    cost_of_call = 0.15 * length_of_call;
  }
  console.log(cost_of_call);
}
costcalculator();

Why is this code not working as I want it to? The cost is not being calculated properly. Using OR instead of AND works, but I'm not sure why does it work. Any clarification?
 
  • #15
When you post code, please make sure you select the right language: [code=javascript]. I have reposted below, adding some console.log statements that will help you work out what is going on.
JavaScript:
function costcalculator() {
  let day_of_the_week = prompt("Enter the day of the week: Su Mo Tu We Th Fr Sa");
  let time_call_started = prompt("Enter the time the call started in the format 14:30");
  const [hour, minute] = time_call_started.split(':');
  let time_call_started_in_minutes = hour * 60 + minute;
  // Is this what you expect?  Why do you think it is a string?
  console.log(time_call_started_in_minutes);
  let length_of_call = prompt("Enter the length of call in minutes");
  let cost_of_call;
  // This works here, but see the note about 'let' and 'const'.
  day_of_the_week_uppercase = day_of_the_week.toUpperCase();
  console.log(day_of_the_week_uppercase);
  // See what happens if you enter "Su"...
  if (day_of_the_week_uppercase = "MO" || "TU" || "WE" || "TH" || "FR") {
    // ...what do you think has happened here?
    console.log('After if', day_of_the_week_uppercase);
    if (time_call_started_in_minutes >= 480 && time_call_started_in_minutes <= 1080) {
      cost_of_call = 0.40 * length_of_call;
    }
    else {
      cost_of_call = 0.25 * length_of_call;
    }
  }
  else {
    cost_of_call = 0.15 * length_of_call;
  }
  console.log(cost_of_call);
}
costcalculator();
It is a good idea to only use let if you are later going to change the value, otherwise use const. If you had used const day_of_the_week_uppercase in line 11 it would have prevented the problem in line 14.
 
  • #16
Honestly, I don;t see why it's easier for us to do your work for you i javascript than for us to do your work for you in C++.

As far as being a hard language to learn, any language is hard to learn if you don't look at the documentation.
 
  • Like
Likes phinds
  • #17
@pbuk
JavaScript:
function costcalculator() {
  let day_of_the_week = prompt("Enter the day of the week: Su Mo Tu We Th Fr Sa");
  let time_call_started = prompt("Enter the time the call started in the format 14:30");
  const [hour, minute] = time_call_started.split(':');
  let time_call_started_in_minutes = Number(hour) * 60 + Number(minute);
  // Is this what you expect?  Why do you think it is a string?
  console.log(time_call_started_in_minutes);
  let length_of_call = prompt("Enter the length of call in minutes");
  let cost_of_call;
  // This works here, but see the note about 'let' and 'const'.
  day_of_the_week_uppercase = day_of_the_week.toUpperCase();
  console.log(day_of_the_week_uppercase);
  // See what happens if you enter "Su"...
  if (day_of_the_week_uppercase == "MO" || "TU" || "We" || "Th" || "Fr") {
    // ...what do you think has happened here?
    console.log('After if', day_of_the_week_uppercase);
    if (time_call_started_in_minutes >= 480 && time_call_started_in_minutes <= 1080) {
      cost_of_call = 0.40 * length_of_call;
    }
    else {
      cost_of_call = 0.25 * length_of_call;
    }
  }
  else {
    cost_of_call = 0.15 * length_of_call;
  }
  console.log(cost_of_call);
}
costcalculator();

I want to keep looping till user doesn't want to exit. How would I do it?
 
  • #18
Vanadium 50 said:
Honestly, I don;t see why it's easier for us to do your work for you i javascript than for us to do your work for you in C++.

As far as being a hard language to learn, any language is hard to learn if you don't look at the documentation.
javascript is very easy compared to c++ where there are built in libraries in javascript to do stuffs and no pointers and stuffs.
 
  • #19
@pbuk I've read a lot about const vs let but I still don't understand what's the difference? I've read in places that const value can be also changed, and saw it being changed while I was learning react and node js. Can you clarify on this?
 
  • #20
Regarding the error in line 14 that @pbuk, take a close look at this page on Javascript operators: https://www.w3schools.com/js/js_operators.asp

shivajikobardan said:
I want to keep looping till user doesn't want to exit. How would I do it?
You need to wrap a loop around the entire block of code that takes user input and calculates the cost of the call. At the bottom of the loop body you will also need to ask whether the user wishes to continue.
 
  • #21
shivajikobardan said:
I want to keep looping till user doesn't want to exit. How would I do it?
Jeez, fella, this is NOT about C++ vs Javascript, it's VERY basic programming. I'm getting the impression that you don't make much effort to solve your own problems before asking us to do it for you.

We're here to help, and are happy to help, but you really should be making more effort on your own.
 
  • Like
Likes Vanadium 50
  • #22
shivajikobardan said:
javascript is very easy compared to c++ where there are built in libraries in javascript to do stuffs and no pointers and stuffs.
First, it doesn't matter how easy it is for you if you have us do the work for you.

Second, this does not require "pointers and stuff" other than if you decide to use a function that changes one of its input variables. This has been explained to you in a previous thread.

Lastly, C++ has it's own extensions. What do you think "using namespace std" does? Just because you refuse to look at them doesn't mean they aren't there.
 
  • Like
Likes phinds
  • #23
JavaScript:
function costcalculator() {
  let shouldContinue = true;
  while (shouldContinue) {

    let day_of_the_week = prompt("Enter the day of the week: Su Mo Tu We Th Fr Sa");
    let time_call_started = prompt("Enter the time the call started in the format 14:30");
    const [hour, minute] = time_call_started.split(':');
    let time_call_started_in_minutes = Number(hour) * 60 + Number(minute);
    // Is this what you expect?  Why do you think it is a string?
    console.log(time_call_started_in_minutes);
    let length_of_call = prompt("Enter the length of call in minutes");
    let cost_of_call;
    // This works here, but see the note about 'let' and 'const'.
    day_of_the_week_uppercase = day_of_the_week.toUpperCase();
    console.log(day_of_the_week_uppercase);
    // See what happens if you enter "Su"...
    if (day_of_the_week_uppercase == "MO" || "TU" || "We" || "Th" || "Fr") {
      // ...what do you think has happened here?
      console.log('After if', day_of_the_week_uppercase);
      if (time_call_started_in_minutes >= 480 && time_call_started_in_minutes <= 1080) {
        cost_of_call = 0.40 * length_of_call;
      }
      else {
        cost_of_call = 0.25 * length_of_call;
      }
    }
    else {
      cost_of_call = 0.15 * length_of_call;
    }
    console.log(cost_of_call);
    inputState = prompt("Do you want to continue Y or N");
    if (inputState.toUpperCase() == "Y") {
      shouldContinue = true;
    }
    else {
      shouldContinue = false;
    }
  }
}
costcalculator();

Problem is solved.
 
  • #24
And with 1/10 as many lines.

Code:
struct std::tm tm;
std::istringstream theTimeString("10:30");
theTimeString >> std::get_time(&tm, "%H:%M");
std::time_t time = mktime(&tm);
 
  • Like
Likes jtbell and phinds
  • #25
Vanadium 50 said:
And with 1/10 as many lines.

Code:
struct std::tm tm;
std::istringstream theTimeString("10:30");
theTimeString >> std::get_time(&tm, "%H:%M");
std::time_t time = mktime(&tm);
and 1/10 readability.
 
  • Like
Likes PeroK
  • #26
shivajikobardan said:
and 1/10 readability.
Only if you're not familiar w/ programming
 
  • Like
Likes Vanadium 50 and berkeman
  • #27
Thread paused for Moderation...
 
  • #28
Okay, thread is done. Thanks all for helping the OP.
 
  • #29
[Moderator's note: Post merged after thread close since it does add a substantive response to a question asked earlier in the thread.]

shivajikobardan said:
I've read a lot about const vs let but I still don't understand what's the difference?
When you declare a variable with const you cannot reassign it, but if it is assigned to an object you can change it's properties.
JavaScript:
// This will fail:
const n = 1;
n = 2;
// But this will succeed:
const thing = { property: false };
thing.property = true;
// And so will this (arrays are objects too).
const things = ['The meaning of life'];
things[0] = 42;

shivajikobardan said:
I've read in places that const value can be also changed, and saw it being changed while I was learning react and node js. Can you clarify on this?
You must have seen the const object's properties being changed as above.
 
Last edited by a moderator:
  • Like
Likes FactChecker

1. How do I take user input in hh:mm format in C++?

To take user input in hh:mm format in C++, you can use the cin function and specify the input format using the setw() function from the iomanip library.

2. How can I parse the input in hh:mm format into hours and minutes in C++?

To parse the input in hh:mm format into hours and minutes in C++, you can use the substr() function to extract the hours and minutes as substrings from the input string. Then, you can convert the substrings to integers using the stoi() function.

3. What is the difference between hh:mm and HH:MM format in C++?

The difference between hh:mm and HH:MM format in C++ is that hh:mm format represents time in 12-hour format with an "am" or "pm" indicator, while HH:MM format represents time in 24-hour format without any indicator.

4. How do I handle invalid input in hh:mm format in C++?

To handle invalid input in hh:mm format in C++, you can use conditional statements to check if the input is in the correct format and within the valid range of hours and minutes. If the input is invalid, you can prompt the user to enter a valid input.

5. Can I convert the input in hh:mm format to seconds in C++?

Yes, you can convert the input in hh:mm format to seconds in C++ by multiplying the hours by 3600 and adding it to the minutes multiplied by 60. This will give you the total number of seconds represented by the input time.

Similar threads

  • Engineering and Comp Sci Homework Help
Replies
4
Views
574
  • Engineering and Comp Sci Homework Help
2
Replies
43
Views
4K
  • Programming and Computer Science
Replies
2
Views
1K
  • Programming and Computer Science
Replies
10
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
1
Views
1K
  • Programming and Computer Science
Replies
2
Views
314
  • Engineering and Comp Sci Homework Help
Replies
1
Views
8K
  • Engineering and Comp Sci Homework Help
Replies
8
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
7
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
9
Views
2K
Back
Top