Kyle Sanchez Kyle Sanchez - 1 year ago 72
C Question

CGI- Getting the mean of 10 inputs given by user thru HTML

For our homework, we had to create an HTML that gets 10 inputs from user using forms. Then, from those 10 inputs, we had to create a program that gets the mean of the 10 inputs and then display the results. This is what I've done so far:
We had to store those 10 inputs in an array first

CGI code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void)
char *data;
int i;
int nums[10];
double sum = 0.0;
double size=0.0;

for(i=0; i<10; i++)
sscanf(data,"nums[i]=%d", &nums[i]);
sum += nums[i];
printf("The average is %d\n",size);
return 0;

And the HTML:

<form action='/cgi-bin/trust.cgi'>
<a: input type=text value='' name=a />
<b: input type=text value='' name=b />
<c: input type=text value='' name=c />
<d: input type=text value='' name=d />
<e: input type=text value='' name=e />
<f: input type=text value='' name=f />
<g: input type=text value='' name=g />
<h: input type=text value='' name=h />
<i: input type=text value='' name=i />
<j: input type=text value='' name=j />
<input type=submit value='Compute'>

QUESTION: I keep getting "Error 500: Server error! Premature end of script headers: trust.cgi". This is my first time coding this type of code and I would appreciate any help.

EDIT: taken care of that Error 500. But now my problem is that it's giving me the wrong answers for the average that I need? Any help? Thanks!

Answer Source

The 500 error is caused by an incorrect HTTP header. According to RFC 2616, the headers of an HTTP response should be separated from the response body by two CRLF line breaks (i.e., "\r\n\r\n"). You can fix this by changing the first printf() statement to:

printf("Content-Type: text/html\r\n\r\n");

(Edit: The CGI specification is not as strict — all you need is a blank line between the headers and body, so presumably "\n\n" will also work.)

Also, your parsing code is completely wrong. Your match string of nums[i]= passed to sscanf() will only match numsi=, which appears nowhere in the query string. Also you are passing the same input string (data) to sscanf() every time. Try using strsep() instead.

Finally, you are trying to print the result (double size;) as an integer ("%d"). You should use a format specifier of "%f" instead.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download