Search code examples
c++charstring-literals

Print character in a for loop c++


This is a pretty basic question as I am new to the C++ language but I have a program that takes a function to print a single character in a for loop. My code is shown below:

void printBar(const char symbol, int count){
    for (int i = 0;i <= count; i++){
        cout << symbol;
    }
}

and my main function is this:

int main(){
    int size = 8;
    const char* sym = "*":
    printBar(sym,size);

I want my result to look like this:

********

What am I doing wrong here?


Solution

  • You should say what goes wriong. Errors, wrong output.... But I can guess

    First this loop is wrong

    void printBar(const char symbol, int count){
        for (int i = 0;i <= count; i++){
            cout << symbol;
        }
    }
    

    it will print one too many char. You should have i < count

    Second your function needs a char, but you pass in a char*

    Do this

    int main(){
    
    int size = 8;
    const char sym = '*':
    printBar(sym,size);