简体   繁体   中英

Using getline and stringstream to slice string

I'm having trouble slicing a string at the spaces. Here is my code.

#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() just takes an input, puts it into a string, then passes the string to the formatData() function above.

When I run this code with input '08-27-1980 10:56:59', my code breaks at the line "time = segments[1]" and I get a "vector subscript out of range" error. I expect the program to break the input string into two strings and put each string into the vector segments. However, that is not what is happening. What is going on here and how can I fix it?

rawStream is already a string stream so there's a helpful little trick you can try. Instead of using getline to a space you can just use the overloaded >> symbol part of ios.

while(rawStream >> temp){
  ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM