TheRealPdGaming
TheRealPdGaming

Reputation: 65

C++: 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.

 IE: 
    >hello world

 Output:
        he ll ow or ld

Here is what I have.

#include<iostream>
#include<string>
#include<fstream>
#include<vector>

using namespace std;

int main()
{
    string input;

    ifstream infile;
    infile.open("wordpairs.txt");

    while(!infile.eof())
    {
        getline(infile, input);


        for(int i = 0; i < input.length(); i++) //accidentally posted wrong code last time. My apologies.
        {
            cout << input[i] << input[i+1] << " ";
        }
        cout << endl;
    }



    infile.close();
    return 0;
}

Edit & Run

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

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

How do I fix it? I figure it has something to do with my for loop calling input[i + 1], but i dont know how to combine words other than doing that.

Upvotes: 1

Views: 1003

Answers (4)

Devesh Pillai
Devesh Pillai

Reputation: 1

try to use this instead i+=2, in order to avoid repetition. if it reaches length() , then try using i<s.length(). i have taken s as the string here

Upvotes: 0

Killzone Kid
Killzone Kid

Reputation: 6240

This will print anything in pairs of 2 letters:

#include <iostream>

int main()
{
    std::string input = "lo  zpxcpzx zxpc pzx cpxz c  lol";

    for (size_t i = 0, printed = 0; i < input.length(); ++i)
    {
        if (isspace(input[i]))
            continue;

        std::cout << input[i];
        printed++;

        if (printed % 2 == 0)
            std::cout << " ";
    }

    return 0;
}

Prints:

lo zp xc pz xz xp cp zx cp xz cl ol

Upvotes: 2

wally
wally

Reputation: 11012

The following takes two characters at a time and prints them. It uses the for syntax to initialize the chars and then to only proceed if reading two characters was successful.

for(char c1{}, c2{}; infile >> c1 >> c2;) {
    std::cout << c1 << c2 << ' ';
}

Upvotes: 0

Jimmy Guo
Jimmy Guo

Reputation: 1304

try to modify i++ to i+=2, because you need to skip the second as first

Upvotes: 2

Related Questions