如果我向用户询问由破折号分隔的输入,我如何将它们存储到多个变量中?由破折号分隔的每个部分一个。 例如,这是行不通的。
cout << "enter date" << endl;
// user inputs something like 11/11/1980
cin >> month
我知道输入存储在 iostream 中,但我如何存储第一个斜杠后的内容
最佳答案
我认为您应该考虑使用 C++11 已经提供给您的日期工具。
time.h 的 struct tm
有 it's own streaming operators .所以我会做这样的事情:
#include <iostream>
#include <sstream>
#include <iomanip>
#include <ctime>
using namespace std;
int main() {
tm t;
istringstream ss("11/11/1980");
ss >> get_time(&t, "%m/%d/%Y");
cout << t.tm_mon + 1 << ' ' << t.tm_mday << ' ' << t.tm_year << endl;
return 0;
}
我不知道为什么,但值得注意的是 tm.tm_mon
是基于 0 的...
关于c++ - 在C++中将输入分离为多个变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28222325/