我正在尝试将用户输入字符串分解为不同的变量。用户字符串的确切格式必须是“星期二 6:40 PM”。我编写了程序,以便一旦循环到达第一个空格,其余变量将被填充,因为只有日期名称的长度不同。我已经尝试了几次,似乎无法获得任何输出。有人知道为什么吗?
void input( Time & time ){
string inputTime;
string charholder;
string day;
string hour;
string minute;
string amPm;
cout << "Enter a day and time: ";
getline(cin, inputTime);
for (int i = 0; i < inputTime.length() ; i++) {
charholder = inputTime[i];
cout << i << endl;
if (charholder != " ") {
day[i] = inputTime[i];
}
else {
hour[0] = inputTime[i+1];
minute[0] = inputTime[i+3];
minute[1] = inputTime[i+4];
amPm[0] = inputTime[i+6];
amPm[1] = inputTime[i+7];
break;
}
}
cout << day << hour << minute << amPm;
}
编辑:正确代码:
void input( Time & time ){
string inputTime;
char charholder;
string day;
string hour;
string minute;
string amPm;
cout << "Enter a day and time: ";
getline(cin, inputTime);
int i = 0;
while (charholder != ' ') {
charholder = inputTime[i];
i++;
}
day = inputTime.substr(0,i);
hour = inputTime.substr(i,1);
minute = inputTime.substr(i+2,2);
amPm = inputTime.substr(i+5,2);
}