8

Before I ask my question let me just say that I am a newbie to C, and do not know how to do a lot in it.

Anyway, the problem is that I need to print a specific number of characters. I first used Python, because that was a language that I was familiar with, and wrote this very simple program.

x = 5    
print('#' * x)

This is what I want to achieve, but in C. Sorry if this is a duplicate or a stupid question, but I have been puzzled and without answers, even after looking on the internet.

Argarak
  • 93
  • 1
  • 2
  • 6
  • 1
    Sorry, C is a low-level system language. It doesn't really even have "strings" as a data type. You have to do all that yourself: allocate a character array, copy characters into it with a loop, even add the null terminator at the end. No shortcuts. – Lee Daniel Crocker Feb 11 '15 at 22:59

3 Answers3

5
for ( size_t ii = 0; ii < 5; ++ii )
    putchar('#');
M.M
  • 138,810
  • 21
  • 208
  • 365
4

Use a loop to print it multiple times.

In C, a symbol between '' has a type char, a character, not a string. char is a numeric type, same as int but shorter. It holds a numerical representation of the symbol (ASCII code). Multiplying it with an integer gives you an integer.

A string, contained between "" is an array of characters. The variable will store a pointer to the first character.

ftynse
  • 787
  • 4
  • 9
  • 6
    In C character constants are of type `int`. You probably confusing with C++. – Grzegorz Szpetkowski Feb 11 '15 at 22:25
  • 1
    Well, I may have oversimplified. But an explanation of what is an implementation-defined behavior and how it is supposed to work for 'ab' or for multibyte characters does not belong to this question. For curious, http://stackoverflow.com/questions/20764538/type-of-character-constant – ftynse Feb 11 '15 at 22:29
  • 1
    @ftynse: Type of character constants is not implementation-defined. It is *always* `int` (C99, `6.4.4.4p10`); for wide constants, it is `wchar_t` (`p11`). – Tim Čas Feb 11 '15 at 23:05
  • 1
    @ftynse The `sizeof('a') == sizeof(int)` - this is not a implementation-defined behavior issue. "An integer character constant has type `int`." – chux - Reinstate Monica Feb 11 '15 at 23:05
  • Even though I chose another answer to my question, I did like your explanation. Thank you! – Argarak Feb 12 '15 at 17:56
0

First of all, use printf function. It allows you to format your output in the way you like. The way to get result you required is a for loop.

int i, x = 5;
for (i = 0; i < x; i++)
    printf("#");
bottaio
  • 4,963
  • 3
  • 19
  • 43
  • Using `printf` to in a loop to print individual characters is overkill; here `putchar` would suffice. – Arkku Feb 11 '15 at 23:10