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:
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;
}