Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

std::regex issue



  • hello, i trying to split a string witch contains a space into 2 parts..
    i have the following code.

            std::string str{""};
            getline(cin, str);
    
            std::vector<std::string> tokens;
            std::regex re(" ");
    
            //start/end points of tokens in str
            std::sregex_token_iterator
            begin(str.begin(), str.end(), re),
            end;
    
            std::copy(begin, end, std::back_inserter(tokens));
    
            string first_value = tokens[0];
            std::cout << "first_value: " << first_value << std::endl;
    
            string second_value = tokens[1];
            std::cout << "second_value" << second_value << std::endl;
    

    this is what the console outputs:

    sadd asdda // test string 1
    first_value:  
    terminate called after throwing an instance of 'std::logic_error'
      what():  basic_string::_M_construct null not valid
    

    according to debug mode:
    the first value = ""
    the second value = " \020" // 16 0x10

    what's going on?


  • Lifetime Qt Champion

    Hi,

    Using a regular expression in this case seems overkill.

    What about the solution proposed in this Stack Overflow answer ?

    Note that QString has a split method that would suite your purpose pretty nicely.



  • @SGaist
    hi, thnx for your reply,

    afterwards, i found this one.
    https://stackoverflow.com/questions/5844657/splitting-a-c-string-into-two-parts

            size_t found = str.find(" ");
            if(found != string::npos) {
                string temp1 = (str.substr(0,found));
                string temp2 = (str.substr(found+1, string::npos));
            }
    

    it did the job.

    i can't use the QT parts for these assignments.


Log in to reply