Parsing a string with a colon and setting both sid

2020-05-10 09:11发布

问题:

So I am trying to write a simple program that takes the time input by the user, and calculates the angles between and around the hands of an analog clock. I have run the program without parsing and 2 separate inputs but I wanted to parse the time at the colon (say, 12:35) and set the left side to an hour variable and the right side to a minutes variable. However, reading examples is hard when you don't know what some of the lines of code mean. Would somebody help me with an example and explain what each line is doing and why use that method?

回答1:

This is what you are looking for:

string time = "12:35";
unsigned int hour, minutes;

sscanf(time.c_str(), "%2d:%2d", &hour, &minutes);

cout << "Hour: " << hour << endl;
cout << "Minutes: " << minutes << endl;


回答2:

Are you looking for something like this:

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

It inputs the hours first, then the colon character, then the minutes.



标签: c++ parsing