2

I was just playing around with c++ and decided to make a text based RPG. I created a method to get info from the user and change it to lower case. This is the function:

std::string getInfo_ToLower(std::string whatToSay) {

    std::string a = "";
    std::cout << whatToSay << std::endl;
    getline(std::cin, a);

    for(int i = 0; i < a.length(); i++){
        a[i] = putchar(tolower(a[i]));
    }
    return a;
};

Im working on Xcode if that helps. So, is there any reason that this method would only work every other time I called it and is there a reason my "return a;" is printing to the console?

Thanks.

  • As a replacement for the tolower loop, see http://stackoverflow.com/questions/313970/how-to-convert-stdstring-to-lower-case . Try to avoid C-style function if you want somewhat "pure" C++. – finite graygreen May 07 '15 at 17:45
  • Thank you Praetorian. That fixed the issue. Still have the weird problem with it only working every other time I call it. Thanks for the help! – JeffreyWorley May 07 '15 at 17:47

2 Answers2

2

Your code calls putchar as it goes through the string a, but the result is buffered. If you want it to become visible right away, add call of fflush:

for(int i = 0; i < a.length(); i++){
    a[i] = putchar(tolower(a[i]));
}
fflush(stdout);
return a;

Note that the way you do printing and conversion at the same time is highly non-intuitive. You would be better off printing the result separately, like this:

// There are better ways to do this, but just to illustrate the point
// let's keep the loop in place
for(int i = 0; i < a.length(); i++){
    a[i] = tolower(a[i]);
}
cout << a << flush;
return a;
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0

Why is it necessary to use put char? Wouldn't cout do it better?

for(int i = 0; i < a.length(); i++){
    a[i] = tolower(a[i]);
}
std::cout << a <<std::endl;
Valentin H
  • 7,240
  • 12
  • 61
  • 111
  • Yeah. I'm very new to programming and i misunderstood the use of putchar. I took it out and it fixed the problem with it printing to the console when i didn't want it to. – JeffreyWorley May 07 '15 at 17:49