我的代码存在问题,涉及如何获取表示时间的字符串数据成员,按其保留的冒号数处理,然后分离并转换为整数。
目标: 花一段时间,以##:##:##:##的形式表示,用1到3个冒号分隔,例如1:13:0:59,并且“切断”冒号之间的各个部分。 / p>
可以省略0的前导日和小时字段,因此0:0:0:12,0:0:12和0:12都是“12秒”的可接受输入形式。 “12”是不可接受的。但是,值可能超过秒,分钟和小时的常规限制。例如,25:3:90和1:1:4:30。
当我输入说的0:01,分钟得到整个值。我不确定另一种方法来分解字符串并从中创建单独的整数。
到目前为止,这是我的代码。
struct Times {
int days;
int hours;
int minutes;
int seconds;
string time;
void string_to_ints(string& s);
}
void string_to_ints(string& s) {
// count the amount of colons
for (int i = 0; i < time.length(); i++) {
if (time[i] == ':')
count++;
}
// initialize days hours minutes and seconds
if (count == 3) {
day = time.substr(0, ':');
d = day.size();
hour = time.substr( d+1, ':');
h = hour.size();
min = time.substr( h+1, ':');
m = min.size();
sec = time.substr( m);
ss= time.size();
}
// initialize hours, minutes and seconds
if (count == 2) {
hour = time.substr( 0, ':');
h = hour.size();
min = time.substr( h+1, ':');
m = min.size();
sec = time.substr( m);
ss = time.size();
}
// initialize minutes and seconds
if (count == 1) {
min = time.substr(0, ':');
m = min.size();
sec = time.substr( m );
ss = time.size();
}
// convert the strings to integers
stringstream buffer(sec);
buffer >> seconds;
stringstream buffer2(min);
buffer2>> minutes;
stringstream buffer3(hour);
buffer3 >> hours;
stringstream buffer4(day);
buffer4 >> days;
感谢您的帮助。
答案 0 :(得分:1)
也许,这样的事情?
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <cstdlib>
#include <algorithm>
using namespace std;
int main() {
string time_str = "1:13:0:59";
istringstream iss(time_str);
string temp;
int days = 0, hours = 0, minutes = 0, seconds = 0;
size_t ndelims = count(time_str.begin(), time_str.end(), ':');
int count = 0;
if (ndelims == 3) {
while(getline(iss, temp, ':')) {
cout << atoi(temp.c_str()) << endl;
if (count == 0) {
days = atoi(temp.c_str());
}
else if(count == 1) {
hours = atoi(temp.c_str());
}
else if(count == 2) {
minutes = atoi(temp.c_str());
}
else if (count == 3) {
seconds = atoi(temp.c_str());
}
count = count + 1;
}
cout << days << " " << hours << " " << minutes << " " << seconds << endl;
}
else if (ndelims == 2) {
while(getline(iss, temp, ':')) {
cout << atoi(temp.c_str()) << endl;
if(count == 0) {
hours = atoi(temp.c_str());
}
else if(count == 1) {
minutes = atoi(temp.c_str());
}
else if (count == 2) {
seconds = atoi(temp.c_str());
}
count = count + 1;
}
cout << days << " " << hours << " " << minutes << " " << seconds << endl;
}
else if(ndelims == 1) {
while(getline(iss, temp, ':')) {
cout << atoi(temp.c_str()) << endl;
if(count == 0) {
minutes = atoi(temp.c_str());
}
else if (count == 1) {
seconds = atoi(temp.c_str());
}
count = count + 1;
}
cout << days << " " << hours << " " << minutes << " " << seconds << endl;
}
return 0;
}
这可以通过计算字符串中分隔符(':')
的数量,并将其分解为其成分标记(这将是找到的分隔符数+ 1)来实现。
然后,意识到最右边的标记总是秒,下一个最右边是分钟等,我们可以编写如上所示的代码,,它提供了你想要的解决方案。
答案 1 :(得分:0)
使用strtok将分隔符拆分为“:”。 这适用于char数组。所以你将不得不使用一些哄骗。