The "Help gaasc to learn to code properly" thread

gaasc

Desperately looking for a title
Joined
Apr 26, 2008
Messages
9,834
Location
Honduras
Car(s)
3 of them
I've been having a few problems in my programming class lately so i thought that maybe all of you generous people of FG could help me sort them out so i don't fuck up in the future.

The ghost problem of today;

Code:
#include <stdio.h>
#include <windows.h>

char nom[28] , ser[1];
int vel ;
double imp, total, subt;

main ()
{
printf ("\t KJT Networks \n");
printf ("\t *** ******** \n");
printf ("\t\n (A) Servicio de Dial-up");
printf ("\t\n (B) Internet dedicado");
printf ("\n\n Nombre del cliente: ");
gets ("nom");
printf ("\t\n servicio deseado: ");
scanf ("%s", ser);
system ("CLS");
if (ser == "A")
{
printf ("\tKJT Networks\n");
printf ("\t*** ********\n");
printf ("\n\n\nNombre de el cliente: %s", nom);
subt = 350;
imp = subt + (subt*0.12);
total = subt + imp ;
printf ("\nSubtotal: %.2f", subt);
printf ("\nImpuesto : %.2f", imp);
printf ("\nTotal: %.2f", total);
}
else
{
printf ("\tKJT Networks\n");
printf ("\t*** ********\n");
printf ("\t\nSeleccione el servicio deseado");
printf ("\t\n[1] Internet de 128 Kb");
printf ("\n\t[2] Internet de 256 Kb");
printf ("\n\t[3] Internet de 512 Kb");
printf ("\n\t[4] Internet de mas de 512 Kb");
printf ("\n\n\t Seleccione su servicio: ");
scanf ("%d", vel);
system ("CLS");
if (vel == 1)
subt = 1300;
else
if (vel == 2)
subt = 1500;
else
if (vel == 3)
subt = 1800;
else
subt = 2750;
printf ("\nSubtotal: %.2f", subt);
printf ("\nImpuesto : %.2f", imp);
printf ("\nTotal: %.2f", total);
}
return 0 ;
}

Compiler says 0 errors, 0 warnings, yet it doesn't run properly.

Thanks in advance to everyone that replies ;)
 
Last edited by a moderator:
One thing jumping up is you're trying to store a string in a one-element char array - that is only large enough for the string terminator 0.
 
Eh? I've got so much to learn,what exactly is the problem again. Sorry for not understanding.
 
In C a string of length x needs x+1 byte to be stored because every string is terminated with the null character.
For example, if you store "abc" you would need four byte, or a char[4] array. Your array ser is only one element, so it can at most store the empty string "". Filling it with any longer string will cause undefined behavior.
 
Alright did some tweaking per narf's suggestion and ended up with

Code:
#include <stdio.h>
#include <windows.h>

char nom[28] ,*ser;
int vel ;
double imp, total, subt;

main ()
{	
	printf ("\t KJT Networks \n");
	printf ("\t *** ******** \n");
	printf ("\t\n (A) Servicio de Dial-up");
	printf ("\t\n (B) Internet dedicado");
	printf ("\n\n Nombre del cliente: ");
	scanf ("%s", nom);
	printf ("\t\n servicio deseado: ");
	gets ("ser");	
	system ("CLS");
	if (ser == "A")
	{
		printf ("\tKJT Networks\n");
		printf ("\t*** ********\n");
		printf ("\n\n\nNombre de el cliente: %s", nom);
		subt = 350;
		imp = (subt*0.12);
		total = subt + imp ;
		printf ("\nSubtotal: %.2f", subt);
		printf ("\nImpuesto: %.2f", imp);
		printf ("\nTotal: %.2f", total);
	}
	else
	{
			printf ("\tKJT Networks\n");
			printf ("\t*** ********\n");
			printf ("\t\nSeleccione el servicio deseado");
			printf ("\t\n[1] Internet de 128 Kb");
			printf ("\n\t[2] Internet de 256 Kb");
			printf ("\n\t[3] Internet de 512 Kb");
			printf ("\n\t[4] Internet de mas de 512 Kb");
			printf ("\n\n\t Seleccione su servicio: ");
			scanf ("%d", vel);
			system ("CLS");
			if (vel == 1)
				subt = 1300;
			else
				if (vel == 2)
				subt = 1500;
			else
				if (vel == 3)
				subt = 1800;
			else
				subt = 2750;
			printf ("\nSubtotal: %.2f", subt);
			printf ("\nImpuesto: %.2f", imp);
			printf ("\nTotal: %.2f", total);
	}
			return 0 ;	
}

it still crashes before the first system ("CLS")
 
If gets() is the regular old standard gets() procedure then you're feeding it a wrong parameter. It expects to get a pointer of type char (or char array) to store the value it reads. You're passing some string that is unrelated to any of your variables. I believe you meant to pass ser, not "ser".

The way you initialize ser right now will also cause problems, because while you say it is a pointer to some char, you never say where it points to or never make sure that it actually points to available memory. Just use the way you had before, with a larger number than one.
 
that solves it, Thanks!
 
Last edited:
new problem:
Code:
#include <stdio.h>
#include <windows.h>

int ord, pre,subt = 0;
float imp, total;
char nom [30], ad, add;

main ()
{
	while (ord < 6 || ord > 7)
	{
	printf ("\t Restaurante FG \n");
	printf ("\t *********** ** \n");
	printf ("[1] Papas Fritas ------ 25.00 \n");
	printf ("[2] Hamburgesa -------- 40.00 \n");
	printf ("[3] Nuggets ----------- 30.00 \n");
	printf ("[4] Pollo ------------- 40.00 \n");
	printf ("[5] Refresco ---------- 25.00 \n");
	printf ("[6] Salir");
	subt = 0;
	printf ("\n Su nombre: ");
	scanf ("%s", &nom);
	printf ("\n Seleccione su pedido: ");
	scanf ("%d", &ord);	
	
		switch (ord)
		{
		case 1:
		case 5:
			pre = 25;
			printf ("Desea ordenar algo mas s/n");
			scanf ("%s", &ad);
			break;
		case 2:
		case 4:
			pre = 40;
			printf ("Desea ordenar algo mas s/n: ");
			scanf ("%s", &ad);
			break;
		case 3:
			pre = 30;
			printf ("Desea ordenar algo mas s/n: ");
			scanf ("%s", &ad);
			break;
		case 6:
			printf ("Gracias \n");
			break;
		default:
			printf ("Seleccion no es Valida\n: " );
		break;
		}
		subt = subt + pre;
		while (ad == 's' || ad == 'S')
		{
		switch (ad)
		{
		case 'S':
		case 's':
			printf ("Que desea ordenar");
			scanf ("%d", &ord);
			subt = subt + pre;
			switch (ord)
		{
		case 1:
		case 5:
			pre = 25;
			printf ("Desea ordenar algo mas s/n");
			scanf ("%s", &ad);
			break;
		case 2:
		case 4:
			pre = 40;
			printf ("Desea ordenar algo mas s/n");
			scanf ("%s", &ad);
			break;
		case 3:
			pre = 30;
			printf ("Desea ordenar algo mas s/n");
			scanf ("%s", &ad);
			break;
			default:
			printf ("Seleccion no es Valida\n");
		break;
		case 'n':
		case 'N':
			system ("CLS");
			printf ("\t Restaurante FG \n");
			printf ("\t *********** ** \n");
			printf ("\n\n\nNombre: %s", nom);
			imp = (float)subt*0.12;
			total = (subt +  imp);
			printf ("\nImpuesto: %.2f ", imp);
			printf ("\nTotal: %.2f", total);
			system ("PAUSE");
			}
			}
		}
				
	}
		
	return 0;
}

I can't get this thing to work properly, any ideas?
 
tl;dr

Check whether it's an input issue or a processing issue by filling the input variables in the source code instead of by typing during execution.
 
I'd recommend to learn to use the debugger, I resisted it for a long time but once I actually figured it out, it was so useful.

EDIT: Also a general idea of what happens when you try to run it would be helpful.
 
Last edited:
lol @ the 'do someone else's homework' thread.

Seriously. Figure it out yourself or you'll never learn.
I'd recommend to learn to use the debugger, I resisted it for a long time but once I actually figured it out, it was so useful.

EDIT: Also a general idea of what happens when you try to run it would be helpful.

Seconded. Debuggers are your friend, especially the friendly GUI ones that show you what line is being run and whatnot. If you haven't used it yet, try Netbeans.
 
I'm actually quite good at it, if it was the ?Do my homework thread? I'd have a new program here everyday. My exams sometimes are used as a ?This is how you do it? example in class and all the sort of thing. But sometimes there are stuff that I just can't solve. It becomes especially irritating when it turns out it's a really simple thing like putting %c on a place where %s should be and all that.

Besides if you stare at a program for a couple of hours and cant figure what's wrong with it, chances are you're not going to figure it out anytime soon.

Well, at least narf and thevictor390 get it.
 
Damn, looking at this stuff reminds me how much I've forgotten about programming :(

Near the top, you have one case of initializing multiple variables on a line without a space after the comma, does that matter? If I can get a compiler going I will try to be more helpful, I need to keep myself up anyway.

EDIT: Ignore the above, the program compiles fine. Now if you'll excuse me, I'm off to learn Spanish.

EDIT EDIT: ok, it just seems to loop once you are done with your order.

I will just keep editing now:

It looks like you initiate a while loop before assigning a value to ord. You should initialize it at 0 or something. Right now it will probably work since whatever garbage it gets thrown into will most likely be less than 6 or more than 7 anyway. I think.

More edits: I think you are missing a closing brace "}" towards the end, in all your switches.


Ignore my ramblings. I would recommend being consistent with indentation and braces, it makes things easier to read. I cleaned it up a bit and noticed that near the end, you had a while loop for when ad = s, but in that while loop, you had a switch for ad = s or n. Removed the switch, put the s part in the while loop and the rest outside it and it seems to work now. Actually, might as well just make that an if/else since that's all it's doing. I'm just going to stop before I break your code more.

My above point about initializing ord before using it still stands.

Code:
#include <stdio.h>
#include <windows.h>

int ord = 0, pre, subt = 0;
float imp, total;
char nom [30], ad, add;

main () {
    while (ord < 6 || ord > 7) {
          printf ("\t Restaurante FG \n");
          printf ("\t *********** ** \n");
          printf ("[1] Papas Fritas ------ 25.00 \n");
          printf ("[2] Hamburgesa -------- 40.00 \n");
          printf ("[3] Nuggets ----------- 30.00 \n");
          printf ("[4] Pollo ------------- 40.00 \n");
          printf ("[5] Refresco ---------- 25.00 \n");
          printf ("[6] Salir");
          
          subt = 0;
          printf ("\n Su nombre: ");
          scanf ("%s", &nom);
          printf ("\n Seleccione su pedido: ");
          scanf ("%d", &ord);    
    
          switch (ord) {
                 case 1:
                 case 5:
                      pre = 25;
                      printf ("Desea ordenar algo mas s/n");
                      scanf ("%s", &ad);
                      break;
                 case 2:
                 case 4:
                      pre = 40;
                      printf ("Desea ordenar algo mas s/n: ");
                      scanf ("%s", &ad);
                      break;
                 case 3:
                      pre = 30;
                      printf ("Desea ordenar algo mas s/n: ");
                      scanf ("%s", &ad);
                      break;
                 case 6:
                      printf ("Gracias \n");
                      break;
                 default:
                      printf ("Seleccion no es Valida\n: " );
                      break;
          }
          
          subt = subt + pre;
          while (ad == 's' || ad == 'S') {

                            printf ("Que desea ordenar");
                            scanf ("%d", &ord);
                            subt = subt + pre;
                            switch (ord) {
                                   case 1:
                                   case 5:
                                        pre = 25;
                                        printf ("Desea ordenar algo mas s/n");
                                        scanf ("%s", &ad);
                                        break;
                                   case 2:
                                   case 4:
                                        pre = 40;
                                        printf ("Desea ordenar algo mas s/n");
                                        scanf ("%s", &ad);
                                        break;
                                   case 3:
                                        pre = 30;
                                        printf ("Desea ordenar algo mas s/n");
                                        scanf ("%s", &ad);
                                        break;
                                   default:
                                        printf ("Seleccion no es Valida\n");
                                        break;
                            }
          }
          
          system ("CLS");
          printf ("\t Restaurante FG \n");
          printf ("\t *********** ** \n");
          printf ("\n\n\nNombre: %s", nom);
          imp = (float)subt*0.12;
          total = (subt +  imp);
          printf ("\nImpuesto: %.2f ", imp);
          printf ("\nTotal: %.2f", total);
          system ("PAUSE");
    }
return 0;
}
 
Last edited:
Besides if you stare at a program for a couple of hours and cant figure what's wrong with it, chances are you're not going to figure it out anytime soon.

And that's the joy of coding, sometimes weeks spent trying to fix something that turns out to be a typo.

Once you get onto writing practical code it reaches a complexity where you can't just go on the net and get someone else to look through your code for you, 'cause it's huge.
 
And that's the joy of coding, sometimes weeks spent trying to fix something that turns out to be a typo.

Once you get onto writing practical code it reaches a complexity where you can't just go on the net and get someone else to look through your code for you, 'cause it's huge.

Very true, this was only one function and it took me a while to figure out what was going on (language barrier notwithstanding). That's why I mention the debugger. The best person to fix your code is you, since you understand it best.

It's also better to ask specific questions, like "why does my code keep looping back to the menu" ;)
 
new problem:
[snip]bunch of code[/snip]
I can't get this thing to work properly, any ideas?

It's because you just say "this doesn't work, haallp!" that we immediately thought it was a "do my homework for me" thread. If you're not willing to explain exactly what the problem is, where you think it might be, what you think should happen, what actually happens, and what you did already to try to fix it, most of us won't be willing to invest our time in it either. Basically, show us that you're trying, and we'll try too.

I'm actually quite good at it, if it was the ?Do my homework thread? I'd have a new program here everyday. My exams sometimes are used as a ?This is how you do it? example in class and all the sort of thing. But sometimes there are stuff that I just can't solve. It becomes especially irritating when it turns out it's a really simple thing like putting %c on a place where %s should be and all that.

Besides if you stare at a program for a couple of hours and cant figure what's wrong with it, chances are you're not going to figure it out anytime soon.

Well, at least narf and thevictor390 get it.

Believe me, I get it too, but asking us to fix things without giving us any help is off-putting. I have found that the best place for help is in the CS department's computer lab, but feel free to ask here too, just try to make it easy for us: remember, we don't know anything about your program unless you tell us!

Very true, this was only one function and it took me a while to figure out what was going on (language barrier notwithstanding). That's why I mention the debugger. The best person to fix your code is you, since you understand it best.

It's also better to ask specific questions, like "why does my code keep looping back to the menu" ;)

^This^


Basically, it's more important for you to learn how to debug effectively than it is for you to get any one of these programs done quickly. I'll help you, but I'm not going to do it for you, because I know that it would not be doing you any favors in the long run. In my last CS class, I was one of only 8 people out of about 60 to finish one of the main projects (a flight itinerary management program), and the one thing all of us who finished it (and especially the three of us who beat the prof's speed, and thus got extra credit) had in common was that we knew our way around a debugger.

Edit:
It would also help if you used ansi C, with no OS-dependent libraries (unless you really need them). Not all of us are on windows, so by including windows.h, you effectively bar me from actually trying to compile your program. Yes, I know I can simply remove the "system" calls and the windows.h include, but getting help is all about making it easy for the people you are asking.
 
Last edited:
Do you have to do it in C or can you use C++, pretty much every software engineering major(myself included) hates the fuck out of C but like C++ and C#.
 
It's very educational to start with C, it doesn't hold your hand so you understand a lot more of what is happening in the background.
 
I have to do it in C.
I'll also try to describe my programs a lot better next time, and of course I apologize for making you think I wanted you to make my homework.

One interesting thing, With thevictor390's help and some rewriting and practicing, I managed to score a 92 on my programming test.
 
Top