-
Putback() help
Hi!
Im trying to write a code that replaces the first letter of every line with a capital letter.
So for starters that would be the part of the code for replacing.
The problem:
for ex. input : abc
output: aAbBC
It only replaces the last letter and not the first ones.
Maybe im using the wrong funtion for that. Thanks.
Code:
#include <iostream>
using namespace std;
int main()
{
char ch;
cout << "Enter a phrase: ";
while ( cin.get(ch))
{
if (ch == 'a')
cin.putback('A');
if (ch == 'b')
cin.putback('B');
if (ch == 'c')
cin.putback('C');
else
cout << ch;
}
system("PAUSE");
return 0;
}
-
Another example of why good indentation and brace usage will prevent dumb mistakes.
Code:
if (ch == 'a') {
cin.putback('A');
}
if (ch == 'b') {
cin.putback('B');
}
if (ch == 'c') {
cin.putback('C');
} else {
cout << ch;
}
Your 'else' is not the exception to ALL your if statements, only the last one.
-
putback() is not what you want to use. It manipulates cin's buffer so you effectively get to read a character again on the next call to cin.get().
Simply read the first character from cin, convert it to upper case, and output it. Then loop as long as required, reading one character from cin and outputting it without conversion. No need to push things back into cin's buffer at all.
Incidentally, it doesn't really matter in this case (simple code) but it helps if your code indenting matches what the code does. Keep in mind that the compiler ignores indenting.
And system("PAUSE") is windows specific.
-
Thanks a lot Salem and Grumpy , that helped me a lot.
And how do i convert it to upper case without "output()"?
Code:
char ch[222];
cout << "Enter a phrase: ";
while ( cin.get(ch[222]))
{
if (ch[0] == 'a')
{
ch[0] = 'A';
}
Like this?
-
Code:
ch[0] = toupper(ch[0]);
-
Thanks a million Cyberfish! :)
Just what i needed. ;)