reading a string 2 characters at a time

hi guys may i know how do i read a string 2 characters at a time?

lets say i have a for loop like this

1
2
3
4
5
6
7
for(int i=0;i<stringLen;i++)
{
    for(int j=0;j<???;j++)
    {
      //insert code
    }
}

what i want to do is i want to read a string 2 characters at a time and store them into a vector. May i know how do i do this?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// The string we will be working with
std::string str = "Hello, World!";

// The vector we want to store the string in (2 characters per element)
std::vector < std::string > vec;

// Here we store characters until its length == 2, then we add it to vec
std::string temp;

// Loop through all the characters of str
for ( int i = 0; i < str.length(); ++i )
{
    // Add the current character to temp
    temp += str[ i ];

    // If temp's length is equal to 2 (or bigger, but that won't happen)
    if ( temp.length() >= 2 )
    {
        // Add temp to the vector
        vec.push_back( temp );

        // Reset temp
        temp = "";
    }
}

// If the length of str was an odd number, we still have a character left in
// temp, so add that to vec too
if ( temp.length() != 0 )
{
    vec.push_back( temp );
}
Last edited on
Will the length of the string always be an even number?

Andy
no, it won`t always be an even number. it is subjected to the user`s input.

@fransje
Thanks man!
Topic archived. No new replies allowed.