【问题标题】:Using getline and stringstream to slice string使用 getline 和 stringstream 对字符串进行切片
【发布时间】: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


【解决方案1】:

rawStream 已经是一个字符串流,所以你可以尝试一个有用的小技巧。您可以使用 ios 的重载 >> 符号部分,而不是使用 getline 到空格。

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

【讨论】:

    猜你喜欢
    • 2021-03-12
    • 2012-07-13
    • 1970-01-01
    • 2014-07-08
    • 1970-01-01
    • 2012-12-25
    • 1970-01-01
    • 1970-01-01
    • 2021-04-07
    相关资源
    最近更新 更多