Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
154 views
in Technique[技术] by (71.8m points)

c++ - Program that splits strings isn't working?

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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...