Reputation: 13
I am working on a small program that takes uppercase letters and converts them to lowercase. I have this accomplished, but when outputting the result it shows before my text when it should be after. How should I go about fixing this? Thank you.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string users_word;
cout << "Please enter a word: ";
getline(cin, users_word);
cout << "You entered the word: " << users_word << endl;
char i = 0;
char c = 0;
while (users_word[i])
{
c = users_word[i];
putchar(tolower(c));
i ++;
}
cout << "Your word in lowercase is: " << c << endl;
}
The output is:
Please enter a word: Hello
You entered the word: Hello
helloYour word in lowercase is:
I am trying to figure out how to get "hello" afterwards.
Upvotes: 0
Views: 244
Reputation: 1622
Actually the while
loop implicitly
redirects the lower chars to std::out
already.
Thus,
cout << "Your word in lowercase is: " << c << endl;
will appear your lower text in front of Your word in lowercase is:
. Just move the cout << "Your word in lowercase is: ";
before while
statement.
#include <iostream>
#include <string>
using namespace std;
int main()
{
...
cout << "Your word in lowercase is: ";
while (users_word[i])
{
c = users_word[i];
putchar(tolower(c));
i++;
}
cout << endl;
}
Upvotes: 0
Reputation: 598384
By calling putchar()
directly, you are bypassing any buffering that std::cout
does internally. You are outputting characters to the terminal before the cout
buffer is flushed to the terminal.
Also, even if you were using std::cout
instead of putchar()
, you are still outputting the lowercase characters before you output "Your word in lowercase is: "
. You need to output that message before entering your loop, not outputting it after the loop.
Try this instead:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string users_word;
cout << "Please enter a word: ";
getline(cin, users_word);
cout << "You entered the word: " << users_word << endl;
cout << "Your word in lowercase is: ";
for (string::size_type i = 0; i < users_word.size(); ++i)
{
char c = users_word[i];
//putchar(tolower(c));
cout.put(tolower(c));
// or: cout << (char) tolower(c);
}
cout << endl;
}
Upvotes: 1