Why does the code I made have a funky number output? It just converts lower case to upper case and vice versa. It also echos the words you typed in, and leaves out numbers you typed.
#include <iostream>
#include <string>
#include <cctype>
usingnamespace std;
int main()
{
int space;
int letter;
int notLetters;
char ch;
cout << "I will read all keyboard input until you type \"@\" OK" << endl;
cin.get(ch);
while(cin.get(ch) && ch != '@'){
if (isalpha(ch)){
letter++;
if (isupper(ch)){
cout << tolower(ch);
}
elseif (!(isupper(ch))){
cout << toupper(ch);
}
}
elseif (ispunct(ch)){
space++;
}
elseif (!(isalpha(ch))){
notLetters++;
}
cin.get(ch);
}
cin.get();
cout << "You typed in " << letter << " letters, and " << notLetters <<
" things that arent letters. You also typed in " << space << " words.";
cin.get();
cin.get();
}
My first guess is that you have far too many cin.get() calls in your program. You should probably only have one (the one in the while()).
Next be aware of the type of variables the <cctype> functions return (hint: it's not a character). Since you just print those return values they will not be converted to a char.
You should also initialize all your variables before you use them.
Okay thanks. That was my first time using the <cctype> functions. I'll make sure to type cast their return values to char to fix it. Also the cin.get() stop the program from closing immediately in console.
#include <iostream>
#include <string>
#include <cctype>
usingnamespace std;
int main()
{
int space = 0;
int letter = 0;
int notLetters = 0;
char ch;
cout << "I will read all keyboard input until you type \"@\" OK" << endl;
cin.get(ch);
while(cin.get(ch) && ch != '@'){
if ((char)isalpha(ch)){
letter++;
if ((char)isupper(ch)){
cout << (char)tolower(ch);
}
elseif (!((char)isupper(ch))){
cout << (char)toupper(ch);
}
}
elseif ((char)ispunct(ch)){
space++;
}
elseif (!((char)isalpha(ch))){
notLetters++;
}
cin.get(ch);
}
cin.get();
cout << "You typed in " << letter << " letters, and " << notLetters <<
" things that arent letters. You also typed in " << space << " words.";
cin.get();
cin.get();
}
That was my first time using the <cctype> functions. I'll make sure to type cast their return values to char to fix it.
You wouldn't need to cast the return values if you assign the return values to a char.
char ch = toupper(ch);
Your problem is being caused because you're not storing the return value in a char variable. Remember the stream operator will see that function is returning an int and will place the returned value in a temporary int variable for the print.
Also the cin.get() stop the program from closing immediately in console.
This is true only for the very last cin.get(), not the many other cin.get() strewn about the program.