【发布时间】:2017-09-28 11:28:22
【问题描述】:
我无法在空格处分割字符串。这是我的代码。
#include <sstream>
#include <iostream>
#include <vector>
#include <string>
void formatData(std::string rawTime) {
std::stringstream rawStream(rawTime);
std::string month, time, temp, date, timePeriod = "";
int day, year, monthNum;
std::vector<std::string> segments;
while (std::getline(rawStream, temp, ' ')) {
segments.push_back(temp); //now have a vector of {"MM-DD-YYYY", "HH:MM:SS", "XM"}
}
date = segments[0];
time = segments[1];
if (segments.size() > 2)
timePeriod = segments[2];
///code that assigns month, day and year values
std::cout << "You were born on " << month << " " << day << ", " << year << " at " << time; }
main() 只接受一个输入,将其放入一个字符串中,然后将该字符串传递给上面的 formatData() 函数。
当我使用输入“08-27-1980 10:56:59”运行此代码时,我的代码在“时间 = 段 [1]”行处中断,并且出现“向量下标超出范围”错误。我希望程序将输入字符串分成两个字符串并将每个字符串放入向量段中。然而,事实并非如此。这是怎么回事,我该如何解决?
【问题讨论】:
标签: c++ string stream slice getline