I have a chunk of code I want to repeat three times dependent on a (y or n), but it's giving me errors because i didn't tell it to empty out the strings at the end of the chunk. I must have done it before, but everything I try is giving me errors.
How do I clear out a string variable so I can immediately use it again within the same loop?
Try putting this line after each of your cin.getline and cin>> calls:
cin.ignore(500, '\n');
What this does is it goes through the input stream and deletes up to 500 characters or the first newline, whichever comes first. I suspect newlines that remain in the stream are polluting your results.
Also, I don't understand your loop. If the user says no, it would make them do it again if they haven't done it three times yet? Shouldn't it just be the do-while without the for?
#include<iostream>
usingnamespace std;
int main(){
char s1[500], s2[500];
char yorn ;
int k;
for (k = 0; k < 3;) {
do {
cout << "Enter the first string : " << endl << endl;
cin.getline(s1, 500);
cout << endl;
cout << "Enter the second string : " << endl << endl;
cin.getline(s2, 500);
cout << endl;
//if (isAnagram(s1, s2))
// {cout << s1 << " and " << s2 << " are anagrams." << endl << endl;}
//else
// {cout << s1 << " and " << s2 << " are not anagrams."<< endl << endl;}
cout << "Would you like to try another pair? (Y or N) : ";
cin >> yorn;
cout << endl;
k++;
if (k == 3) break; //even if k>3, if user keeps saying yes, it will not break.
// if you want to limit to 3, use this break here
cin.ignore(500, '\n');
} while ((yorn == 'y') || (yorn == 'Y')); //you missed == here.
if (yorn == 'n' || yorn == 'N') break; //if user says No, you should break for loop too.
}
}
OP, you should put cin.ignore(500, '\n'); right after each call to cin.getline as well. The post above only uses it at the end of the loop.
The loop can be implemented as a single do-while (cleaner):
1 2 3 4 5 6 7 8 9 10 11
int k = 0;
do
{
//...
cout << "Would you like to try another pair? (Y or N) : ";
cin >> yorn;
cin.ignore(500, '\n');
cout << endl;
k++;
} while ((yorn == 'y' || yorn == 'Y') && (k < 3));