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

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

How can I take input in hh:mm format in C++?

To take input in hh:mm format in C++, you can use the `std::cin` function along with a colon character as a delimiter. For example:

int hours, minutes;char colon;std::cin >> hours >> colon >> minutes;

How do I verify that the input is in the correct hh:mm format?

To verify that the input is in the correct hh:mm format, you can use the `std::cin.fail()` function to check for input errors and ensure that the colon character is correctly placed. Here's an example:

int hours, minutes;char colon;std::cin >> hours >> colon >> minutes;if (std::cin.fail() || colon != ':' || hours < 0 || hours > 23 || minutes < 0 || minutes > 59) { std::cerr << "Invalid input format." << std::endl;}

How can I parse the input time into separate hours and minutes?

To parse the input time into separate hours and minutes, you can directly extract the values using `std::cin` as shown in the first answer. The variables `hours` and `minutes` will hold the parsed values.

int hours, minutes;char colon;std::cin >> hours >> colon >> minutes;

How do I handle invalid input when parsing hh:mm format in C++?

To handle invalid input, you can use a combination of input validation and error checking. You can check if the input stream is in a failed state and if the colon is in the correct position. Additionally, you can check if the hours and minutes fall within valid ranges:

int hours, minutes;char colon;std::cin >> hours >> colon >> minutes;if (std::cin.fail() || colon != ':' || hours < 0 || hours > 23 || minutes < 0 || minutes > 59) { std::cerr << "Invalid input format." << std::endl; // Handle error appropriately}

Can I use string manipulation functions to parse hh:mm input in C++?

Yes, you can use string manipulation functions to parse hh:mm input. You can read the input as a string and then use functions like `std::stoi` and `std::string::substr` to extract hours and minutes. Here is an example:

#include <iostream>#include <string>int main() { std::string time; std::cin

Back
Top