質問

I'm one of those new guys that learned Java first then came to C++ and a lot of things are weird. I'm trying to access characters of a std::string object in order to recognize spaces (yes, I want to go the hard way first, no regex for now), however I'm getting a segmentation fault error that I can't understand. The error is being thrown upon call of the "getTokens()" function, which calls the toTokenize.at() method which is the one throwing segmentation fault. If someone can point me in the right way, I would be really grateful! Find my code below. Thanks!

#include <iostream>
#include <vector>
#include <string>

std::vector<std::string> getTokens(const std::string& toTokenize) {

    std::vector<std::string> result;

    for (int i=1; i<toTokenize.length(); i++) {
        std::cout << toTokenize.at(i);
    }

}


int main() {

    std::string s ("");

    do {

        std::cout << "\nPlease input a command: ";
        getline(std::cin, s);

        getTokens(s);

    }
    while (s != "exit");

    return 0;
}
役に立ちましたか?

解決

getTokens isn't returning anything

Fixes as follows :-

std::vector<std::string> getTokens(const std::string& toTokenize) {
     //^^make it as void, if nothing is to be returned
    std::vector<std::string> result;

     //start from zero
    for (size_t i=0; i<toTokenize.length(); i++) {
        std::cout << toTokenize.at(i);
    }

return result;
        //^^or return value, however, result isn't used here
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top