Hi I need some help with debugging my program: It should read from the Console, process the input and give it back out:
The error occures after while(scanf("%15s", input) != EOF)
is called the 2nd time. Unfortunately I can't tell you what the error is, because the progam freezes and doesn't give me any Information. I think there is something wrong with the input
var (it is passed multiple times)
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
char* repeat(char c, int n);
char* drawLabel(char* label, int n);
char* drawBarnorm(char* label, int value);
char* drawBar(char* label, double value);
int main(void)
{
char* input;
double numIn;
char buf[] = "";
char* pOutput = &buf[0];
while(scanf("%15s", input) != EOF)
{
scanf("%lf", &numIn);
if (numIn > 1)
{
if (numIn > 30)
{
printf("num to big!\n");
return 0;
}
strcat(pOutput, drawBarnorm(input, (int)numIn));
} else
{strcat(pOutput, drawBar(input, numIn));}
printf("%s\n", pOutput);
}
printf("%s\n", pOutput);
return 0;
}
char* repeat(char c, int n)
{
char* out = (char*)malloc(sizeof(char)*50);
int i, len;
out[0] = '\0';
for (i = 0; i < n; ++i)
{
len = strlen(out);
out[len] = c;
out[len+1] = '\0';
}
return out;
}
char* drawLabel(char* label, int n)
{
if (strlen(label) > n)
{
char* newLabel = (char*)malloc(sizeof(char)*(n+1));
newLabel[0] = '\0';
strncpy(newLabel, label, n);
newLabel[n] = '\0';
return newLabel;
} else if (strlen(label) < n)
{
strcat(label, repeat(' ', n-strlen(label)));
}
return label;
}
char* drawBarnorm(char* label, int value)
{
char* bar = (char*)malloc(sizeof(char)*41);
char* barPart;
bar[0] = '\0';
bar = drawLabel(label, 8);
strcat(bar, "|");
barPart = drawLabel(repeat('#', value), 30);
strcat(bar, barPart);
strcat(bar, "|");
return bar;
}
char* drawBar(char* label, double value)
{
int val = (int)(30.0*value);
return drawBarnorm(label, val);
}
Thank you for helping me out with this.
char* input = malloc(size); /* Allocate memory of your wish */
Allocate memory to input
You have not initialized your pointer.
The pointer should be pointing to some valid memory location to store the value through scanf()
You have to initialize input
or declare it as an array like this
char input[16];
also, you should notice that scanf
does not return EOF
it returns the number of arguments matched, so you have to change
while(scanf("%15s", input) != EOF)
to
while(scanf("%15s", input) == 1)
because while(scanf("%15s", input) != EOF
is always true.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.