0
我一直在研究一個項目,它採用日期格式的用戶輸入,例如「05/10/1996」,然後將其解析爲三個整數。一個月,一天,一年。我在查看函數getline(),但不太清楚如何使用它來一次解析多個對象。有沒有辦法做到這一點與一個while循環?如果是這樣,我會感謝一些幫助,因爲我有點卡住這一點。使用getline函數解析C++中的字符串
我一直在研究一個項目,它採用日期格式的用戶輸入,例如「05/10/1996」,然後將其解析爲三個整數。一個月,一天,一年。我在查看函數getline(),但不太清楚如何使用它來一次解析多個對象。有沒有辦法做到這一點與一個while循環?如果是這樣,我會感謝一些幫助,因爲我有點卡住這一點。使用getline函數解析C++中的字符串
int m,d,y;
char dummy;
cin >> m >> dummy >> d >> dummy >> y;
這裏是的方法之一 -
void split(std::vector<std::string> &tokens, const std::string &text, char sep) {
int start = 0, end = 0;
while ((end = text.find(sep, start)) != std::string::npos) {
tokens.push_back(text.substr(start, end - start));
start = end + 1;
}
tokens.push_back(text.substr(start));
}
用法 -
int main(int argc, const char * argv[]) {
std::vector<std::string> tokens;
std::string *text = new std::string("05/10/1996");
split(tokens, *text, '/');
int first = atoi(tokens[0].c_str());
int second = atoi(tokens[1].c_str());
int third = atoi(tokens[2].c_str());
std::cout<<first<<std::endl;
std::cout<<second<<std::endl;
std::cout<<third<<std::endl;
while (true);
return 0;
}
使用整數變量,其輸出該控制檯上 -
有關高級解決方案/討論 - 請參閱this question。
請參閱http://stackoverflow.com/questions/236129/how-to-split-a-string-in-c關於如何將字符串拆分爲令牌(在這種情況下,您將使用「/」作爲分隔符。) –
好的,謝謝我會檢查出來 – emufossum13