How do I get this fail check to work?

I am not sure how to get this check to work. The program is suppose to take in a string and then print it back to the user reversing every pair of characters. ex: input = 1234, output = 2143.
However when I put in the check, the loop goes on forever because the new value that is re-entered doesn't replace the old value. here is my attempt:

//Tommy Tran 2016
//Assign_3_6_Reverse.cpp
#include <iostream>

using namespace std;
string repeat(string words);
string checkEven(string words);

int main()
{
//request words
string words;
cout << "Please enter an even number of words" << endl;
getline(cin, words);
words = checkEven(words);
repeat(words);
return 0;
}

//check for even numbers
string checkEven(string words)
{
int realLength = words.length();

for(int x=0;x<words.length();x++)
{
if(words[x]==' ')
{
realLength -= 1;//subtract spaces
}
}
while ((realLength%2!=0))//if string is even
{
cin.clear();
//cin.ignore(100,'\n');
cout<<"Invalid value! Not an even number of letters ";
getline(cin, words);
}
return words;
}

//create function
string repeat(string words)
{
for(int i=1;i<words.length();i+=3)//pattern is -1 +3 starting at 1
{
cout << words.at(i);
i--;
cout << words.at(i);
}
return words;
}

Last edited on
1
2
3
4
5
6
7
8
9
10
std::string reverse_pairs( std::string str )
{
    if( !str.empty() )
    {
        using std::swap ;
        for( std::size_t i = 0 ; i < ( str.size() - 1 ) ; i += 2 ) swap( str[i], str[i+1] ) ;
    }

    return str ;
}

http://coliru.stacked-crooked.com/a/0aaf153858547324
Topic archived. No new replies allowed.