Nov 5, 2017 at 12:18am UTC
I am new to C++ and loops give me a hard time.
There is a never ending infinite loop although break statements are include after each case.
Any help would be appreciated.
#include <iostream>
#include <iomanip>
#include <string>
#include <istream>
using namespace std;
int main()
{
int lstring;
int x;
int countWords(string str);
int countConsonant(string str, int);
int consonant;
string str, str2;
char selection;
cout << "Please enter a word, a sentence, or a string of numbers." << endl;
getline(cin, str); //user input
lstring = str.length(); //length of string
str2 = str;
bool another = true;
while (another)
{
cout << "\nUSE THIS MENU TO MANIPULATE YOUR STRING" << endl;
cout << "---------------------------------------" << endl;
cout << "1) Inverse String" << endl;
cout << "2) Reverse String" << endl;
cout << "3) To Uppercase" << endl;
cout << "4) Count Number Words" << endl;
cout << "5) Count Consonants" << endl;
cout << "6) Enter a Different String" << endl;
cout << "7) Print the string" << endl;
cout << "Q) Quit" << endl;
cin >> selection;
switch (selection)
{
case '1':
for (x = 0; x < lstring; x++)
{
if (islower(str[x]))
str[x] = toupper(str[x]);
else if (isupper(str[x]))
str[x] = tolower(str[x]);
}
break;
case '2':
for (x = 0; x < lstring; x++)
{
str[x] = str2[lstring - 1 - x];
}
break;
case '3':
{
for (x = 0; x < lstring; x++)
{
if (islower(str[x]))
str[x] = toupper(str[x]);
}
}
break;
case '4':
cout << "\nThe string \"" << str << "\" has " << countWords(str) << " word(s)" << endl;
break;
case '5':
consonant = 0;
cout << "\nThe number of consonants in the string is " << countConsonant(str, consonant) << "." << endl;
break;
case '6':
cout << "\nEnter a different string : " << endl;
cin.ignore();
getline(cin, str);
break;
case '7':
cout << "\nThe current string is: " << str << endl;
break;
case 'Q':
cout << "\nYou have chosen to quit the program. Thank you!" << endl;
break;
case '9':
cout << "\nInvalid selection. Please try again." << endl;
}
}
//system("PAUSE");
return 0;
}
int countWords(string str)
{
int length = str.length();
int words = 1;
for (int size = 1; length > size; size++)
{
if (str[size] == ' ' && str[size - 1] != ' ')
words++;
}
if (str[0] == ' ')
words--;
return words;
}
int countConsonant(string str, int consonant)
{
int length = str.length();
consonant = 0;
for (int i = 0; i < length; i++)
{
if (str[i] != 'a' && str[i] != 'e' && str[i] != 'i' &&
str[i] != 'o'&& str[i] != 'u' && str[i] != 'A' && str[i] != 'E'
&& str[i] != 'I' && str[i] != 'O' && str[i] != 'U' && str[i] != ' ')
consonant = consonant + 1;
}
return consonant;
}
Last edited on Nov 5, 2017 at 12:20am UTC