Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I've created a program that splits a string into, well, more strings, based around a . So, for instance, say I input the string

Workspace.SiteNet.Character.Humanoid

it is SUPPOSED to print

Workspace
SiteNet
Character
Humanoid

However, it prints

Workspace
SiteNet.Character
Character.Humanoid
Humanoid

This is the code.

#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);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
147 views
Welcome To Ask or Share your Answers For Others

1 Answer

Your problem is the arguments you pass to str.substr

string::substr takes two arguments: the start position, and the length of the substring to extract.

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...