How to output a string two letters at a time?

I am trying to read from a file that contains sentences and output them two letters at a time.
1
2
3
4
5
6
7
IE: 
    >hello world
    >how are toy

Output:
        he ll ow or ld
        ho wa re to y


Here is what I have.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
  
#include<iostream>
#include<string>
#include<fstream>

using namespace std;

int main()
{
  string input;

  getline(cin, input);

  for(int i = 0; i < input.lenght(); i++)
  {
    cout << input[i] << input[i+1] << " ";
  }

  return 0;
}


and this is what it currently outputs for lets say for example, "hello world"

1
2
3
output:
       
        h he el ll lo ow eo or rl ld d


How do I fix it? will I have to somehow use vectors (I am awful at those so I am dreading it)
Last edited on
1
2
3
4
for(int i = 0; i < input.lenght(); i++)
  {
    cout << input[i] << input[i+1] << " ";
  }


i starts at 0, next loop is 1
you want to add 1 to i
@pdgaming

The best way to get every two letters printed, would be.

1
2
3
4
5
int len = input.lenght(); // Best to use actual variable 
for(int i = 0; i < len; i+=2) // Increase i by two's
  {
    cout << input[i] << input[i+1] << " ";
  }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <string>

int main()
{
  std::string input;

  getline(std::cin, input);

  for(std::string::size_type i = 0; i < input.size(); i+=2)
  {
    std::cout << input[i] << input[i+1] << " ";
  }
}

Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>

using namespace std;

int main()
{
    string input;

    getline(cin, input);

    istringstream ss(input);

    for (char ch; ss >> ch; )
    {
        cout << ch;
        if (ss >> ch)
            cout << ch << ' ';
    }

}
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
#include <iostream>
#include <string>
#include <cctype>
using namespace std;

void printEvery( string text, int n, char space )
{
   int countDown = n;
   for ( char c : text )
   {
      if ( isgraph( c ) )        // choose isgraph(), isalpha(), etc.
      {
         if ( !countDown ) { cout << space;   countDown = n; }
         countDown--;
         cout << c;
      }
   }
   cout << endl;
}



int main()
{
   printEvery( "Hello world!", 2, ' ' );
   printEvery( "This is a silly sentence taken in fours", 4, '-' );
}
He ll ow or ld !
This-isas-illy-sent-ence-take-ninf-ours
Topic archived. No new replies allowed.