Home > database >  C Code outputs two characters when I only desire one output (Fix found!) <3
C Code outputs two characters when I only desire one output (Fix found!) <3

Time:11-14

As simple as it sounds. I'm a newb when it comes to c , but I have been following cpp reference and some online tutorials to write code. My code should output a string as "SuCh", but instead it outputs something as "SSuuCChh". Is there a practical error I'm missing?

#include <cctype>
#include <iostream>

using namespace std;

int main()
{
    string mani;
    int L = 0;
    getline(cin, mani);
    for (int i = 0; i<mani.length();i  ){
        if(mani.at(i) == ' '){
            cout << ' ' << flush;
            L = L - 2;
        } else if(L%2==0){
            putchar(toupper(mani.at(i)));
            L  ;
        } else if(L%1==0) {
            putchar(tolower(mani.at(i)));
            L  ;
            }
        }
    return 0;
}

CodePudding user response:

You're calling putchar and using cout, so you're printing each character twice in two different ways.

Eliminate either the call to putchar(), or the cout <<, and you will only get each character once.

CodePudding user response:

From cplusplus's putchar(int) reference:

int putchar ( int character ); Write character to stdout.

It is equivalent to calling putc with stdout as second argument.

So your code should look more like

#include <cctype>
#include <cstdio>
#include <iostream>
#include <string>

int main(void) {
    std::string mani, F;
    getline(std::cin, mani);

    for(int i = 0; i < mani.length; i  ) {
        if(i % 2 == 0) { 
            std::cout << std::toupper(mani.at(i));
        } else {
            std::cout << std::tolower(mani.at(i));
        }
    }

    std::cout << std::endl;
    return 0;
}

Note: Extra includes of and are there to ensure those types are included. They may be able to be removed, however I would leave them. Plus, dropping the std prefix can be dangerous due to certain popular libraries, such as Boost, defining their own versions of the functions and objects.

  • Related