您好我需要一些调试我的程序的帮助:它应该从控制台读取,处理输入并将其退回:
第二次调用while(scanf("%15s", input) != EOF)
后发生错误。不幸的是我无法告诉你错误是什么,因为程序冻结并没有给我任何信息。我认为input
var(它多次传递)
#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);
}
感谢您帮我解决这个问题。
答案 0 :(得分:4)
char* input = malloc(size); /* Allocate memory of your wish */
将内存分配给input
您尚未初始化指针。
指针应指向某个有效的内存位置,以通过scanf()
答案 1 :(得分:3)
您必须初始化input
或将其声明为此类数组
char input[16];
另外,您应该注意到scanf
没有返回EOF
它返回匹配的参数数量,因此您必须更改
while(scanf("%15s", input) != EOF)
到
while(scanf("%15s", input) == 1)
因为while(scanf("%15s", input) != EOF
始终为真。