Reputation: 125
I'm having some unknown problem with using strings. It only happens at the instance of this kind of algorithm:
Source.c
#include <stdio.h>
#include <string.h>
main()
{
int cur, max;
char ast[32];
printf("Enter the triangle's size: ");
scanf("%d", &max);
for(cur = 1; cur <= max; cur++)
{
strcat(ast, "*");
if(cur == 1)
{
printf("\n");
}
printf("%s\n", ast);
}
getch();
}
This happens:
Overview: A program that creates a triangle out of asterisks (*) of an inputted size.
Enter the triangle's size: 5
■ Z☼]vYⁿbv░↓@*
■ Z☼]vYⁿbv░↓@**
■ Z☼]vYⁿbv░↓@*
■ Z☼]vYⁿbv░↓@**
■ Z☼]vYⁿbv░↓@*
It's supposed to look like this:
Enter triangle size: 5
*
**
***
****
*****
I don't know why. Can someone please help? :)
Upvotes: 1
Views: 105
Reputation:
alternative using snprintf:
#include <stdio.h>
#include <string.h>
#define MAX 32
int main(void)
{
unsigned int cur, max;
char ast[32];
printf("Enter the triangle's size: ");
scanf("%d", &max);
if (max > MAX)
return -1;
for(cur = 1; cur <= max; cur++)
{
if(cur == 1)
{
snprintf(ast,2,"*");
printf("\n");
}
else
strlcat(ast, "*",cur + 1);
printf("%s\n", ast);
}
return 0;
}
Upvotes: 0
Reputation: 96258
Your string ast
is not initialized, so it will contain garbage, to which you append stuff.
Init it first - you need a zero terminated string, set the first character to '\0'
.
Upvotes: 5