Jc.kal
Jc.kal

Reputation: 93

c++ splitting up a string

I'm learning c++ by myself with a book and I've gotten stuck on an exercise. I'm supposed to split up a string into two parts, each part is separated by a space, and forget the rest but my code doesn't forget the rest for some reason.

#include <iostream>
#include <iomanip>
#include <string>

using namespace std;

int main(){

string original;
string first;
string second;

bool firstDone = false;
bool secondDone = false;

int firstSpace = 0;
int secondSpace = 0;

cout << "Enter string: ";

getline(cin, original);

cout << "The original string is: " << original << endl;

for(int i = 0; i < original.length(); i++)
{
    if(original[i] == ' ' && !firstDone){
        firstSpace = i;
        firstDone = true;
    }
    else if(original[i] == ' ' && !secondDone){
        secondSpace = i;    
        secondDone = true;
    }
}

cout << "The first space is at: " << firstSpace << endl << "The second space is at: " 
     << secondSpace << endl;

first = original.substr(0, firstSpace);
second = original.substr(firstSpace + 1, secondSpace);

cout << "The first string is: " << first << endl << "The second string is: "
     << second << endl;

return 0;

}

when I run it I get

Enter string: test1 test2 test3

The original string is: test1 test2 test3

The first space is at: 5

The second space is at: 11

The first string is: test1

The second string is: test2 test3

and as you can see the second string is "test2 test3" when it should only be "test2". Can someone point out what I did wrong?

p.s. I'm not very far in the book and many other solutions I found online had a bunch of variables and other functions I'm not familiar with so can we limit the answers to the style I've used (if possible).

Upvotes: 3

Views: 114

Answers (1)

Mustakimur Khandaker
Mustakimur Khandaker

Reputation: 715

actually the substr() second parameter is the length of the string from the starting offset that you mention in first parameter. Do like following:

second = original.substr(firstSpace + 1, secondSpace-(firstSpace+1));

Upvotes: 2

Related Questions