我有一个固定格式的字符串。比方说:
This is 24 day of Aug of 2016
那么,在 C++ 中是否有一种简单的方法(类似于 C 中的 strtol
),以便我可以将数据提取到变量中,如下所示:
day = 24;
month = "Aug";
year = 2016;
最佳答案
您可以使用 std::stringstream
来完成此操作.您可以将字符串加载到 stringstream
中,然后将其读入所需的变量中。它将为您转换为您正在使用的数据类型。例如你可以使用
std::string input = "This is 24 day of Aug of 2016";
std::stringstream ss(input)
std::string eater; // used to eat non needed input
std::string month;
int day, year;
ss >> eater >> eater >> day >> eater >> eater >> month >> eater >> year;
它看起来有点冗长,但现在您不需要使用 find
和 substr
以及转换函数。
关于C++ : Pick portions/data from a string having fixed format,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37483564/