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