简体   繁体   中英

Splitting a string into two different vectors C++

I'm trying to split a string into two different vectors. However, I can't for the life of me figure out what I'm doing wrong.

I have a whole bunch of strings that I'm passing through (parsing through from a.txt file) that looks like this:

01 Sam
02 Pam
03 Lam
04 Ham

I'm trying to pass them into two different vectors

std::vector<std::string> numbers;
std::vector<std::string> names;

Here is part of the code that I wrote down:

std::stringstream linestream(data.at(i));
while (std::getline(linestream, data.at(i), ' ')) { // Split the string by spaces
    int t = 0;

    if (t == 0) {
        numbers.push_back(data.at(i));
        t++;
    }

    if (t == 1) {
        names.push_back(data.at(i));
    }
}

I was hoping the first part (which is the number) would get put into the numbers vector and the second part (which is the name) would get put into the names vector. However, both numbers and names are being put into the names vector for some reason.

Is there a better way to split the two?

Splitting data by spaces is exactly what operator>> does when you read a string. No need for the extra getline , your loop can be simplified to something like this:

std::string numberBuf;
std::string nameBuf;
 
while(linestream >> numberBuf >> nameBuf) {
    numbers.push_back(numberBuf);
    names.push_back(nameBuf);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM