拆分字符串的程序不起作用?

J D*_*Doe -1 c++

我创建了一个程序,将一个字符串拆分成更多字符串,基于一个. So,例如,假设我输入了字符串

Workspace.SiteNet.Character.Humanoid

它是支持打印

Workspace
SiteNet
Character
Humanoid
Run Code Online (Sandbox Code Playgroud)

然而,它打印

Workspace
SiteNet.Character
Character.Humanoid
Humanoid
Run Code Online (Sandbox Code Playgroud)

这是代码.

#include "stdafx.h"
#include <Windows.h>
#include <iostream>
#include <vector>
#include <sstream>
#include <WinInet.h>
#include <fstream>
#include <istream>
#include <iterator>
#include <algorithm>
#include <string>
#include <Psapi.h>
#include <tlhelp32.h>


int main() {
  std::string str;
  std::cin >> str;
  std::size_t pos = 0, tmp;
  std::vector<std::string> values;
  while ((tmp = str.find('.', pos)) != std::string::npos) {
    values.push_back(str.substr(pos, tmp));
    pos = tmp + 1;
  }
  values.push_back(str.substr(pos, tmp));

  for (pos = 0; pos < values.size(); ++pos){
    std::cout << "String part " << pos << " is " << values[pos] << std::endl;
  }
  Sleep(5000);
}
Run Code Online (Sandbox Code Playgroud)

Tim*_*phy 6

您的问题是您传递给的参数 str.substr

string::substr 有两个参数:起始位置和要提取的子字符串的长度.

std::vector<std::string> split_string(const string& str){
    std::vector<std::string> values;
    size_t pos(0), tmp;
    while ((tmp = str.find('.',pos)) != std::string::npos){
        values.push_back(str.substr(pos,tmp-pos));
        pos = tmp+1;
    }
    if (pos < str.length())  // avoid adding "" to values if '.' is last character in str
        values.push_back(str.substr(pos));
    return values;
}
Run Code Online (Sandbox Code Playgroud)