pearbear
pearbear

Reputation: 1055

Substring output not as expected?

Small question. With a string that I converted from a text file using:

std::string content((std::istreambuf_iterator<char>(istr) ), 
                        (std::istreambuf_iterator<char>() ) );

Which when printed, looks like:

@....@........@......@....................@....@...............@..........@..@......
@....@..@@@...@......@.......@@@..........@....@..@@@....@@@...@..........@..@......
@@@@@@.@...@..@......@......@...@.........@....@.@...@..@......@.......@@@@..@......
@....@.@@@@...@......@......@...@.........@....@.@...@..@......@......@...@..@......
@....@.@......@......@......@...@.........@.@@.@.@...@..@......@......@...@.........
@....@..@@@@...@@.....@@.....@@@...........@..@...@@@...@.......@@.....@@@@..@......
....................................................................................

And yet, when I use this code here:

    for (int i = 0; i < (content.length()-6); i++){
        std::string w = content.substr(i, 6);
        std::cout << w << '\n';
    }

I get many substrings as I wanted, but they don't look as I expected. My intent is to have something that looks like this (as an example for the first line):

@....@
......
..@...
...@..
......
......
......
@....@
......
......
...@..
......
..@..@
......

When instead, I get along the lines of:

@....@
....@.
...@..
..@...
.@....
@.....
......
......
......
.....@
....@.
...@..
..@...
.@....

I'm not sure why this could be, perhaps I think substr does something that it does not? I just want to get the first 6 letters of the first line, then the next 6, and the next, and so on continuing onto the second line of the string.

Thanks for the help!

Upvotes: 0

Views: 122

Answers (2)

Brian Neal
Brian Neal

Reputation: 32399

Try i += 6 instead of i++ in your for loop.

Upvotes: 1

Andrew Latham
Andrew Latham

Reputation: 6152

I don't actually know C++, but it looks like you're making substrings (0, 5) then (1, 6) then (2, 7), etc. when you are trying to make substrings (0, 5) then (6, 11) then (12, 17).

Try incrementing i by 6 instead of by 1 each time. So the new code would be

for (int i = 0; i < (content.length()-6); i += 6){
        std::string w = content.substr(i, 6);
        std::cout << w << '\n';
    }

The @ that is getting shifted over in your example is the same @ each time, because you are just snaking along by one character.

Upvotes: 5

Related Questions