Reputation: 101
Here is my code
void display(char ch, int lines, int width);
int main()
{
char c;
int rows, cols;
while (1)
{
scanf("%c %d %d", &c, &rows, &cols);
display(c, rows, cols);
if (c == '\n')
break;
}
}
void display(char ch, int lines, int width)
{
for (int i = 0; i < lines; i++)
{
for (int j = 0; j < width; j++)
printf("%c", ch);
printf('\n');
}
}
I wana like this.
if I input a 2 3
It returns
aaa
aaa
But It didn't work. SO I change like this
void display(char ch, int lines, int width)
{
for (int i = 0; i < lines; i++)
{
for (int j = 0; j < width; j++)
putchar(ch);
putchar('\n');
}
}
It works well. why that code works well?? what is difference between printf and putchar?
Upvotes: 0
Views: 929
Reputation: 300
When you have %c inside the printf, then it will print the character only. But your point is you gave 2 but it prints a, why? see the ASCII table and find the number to char equivalent value from here ASCII Table. on the other hand putchar is just char printer.
Upvotes: -1
Reputation: 222933
printf('\n');
is a mistake, and your compiler should warn you about it. The first argument to printf
should be a string, such as "\n"
, not a character constant, such as '\n'
.
The source code "\n"
represents a string of two characters, the first being a new-line character and the second being a null character that indicates the end of the string. When used in an expression this way, it is automatically converted to a pointer to its first element, and this pointer is passed to printf
.
The source code '\n'
represents a character. Its value is the code for that character. When it is passed to printf
, that value is passed. That is the wrong thing to pass to printf
, which is why your first program did not work.
Upvotes: 2