Unusual behaviour in first C program - c

I am writing a program to work out who should pay what in the household, based upon their income. The desired behaviour is the following:
Print welcome message and ask how many people are in the household.
If the number entered is 10 or below, ask for their names.
Ask for each persons income. <- this is where the issue is
Display total income.
Calculate and display result.
Obviously this program is not complete and I need to stop the user entering negative values, but the biggest problem is that when the user enters each persons income, upon hitting the return key it does not ask for any more user input and the totalEarnings comes out as 0.
I am used to programming in C++ so I'm hoping I've just missed a quirk of C.
main.c
#include <stdio.h>
int main(void){
short numberOfPeople = 0;
char* names[10] = {0,0,0,0,0,0,0,0,0,0};
float earnings[10] = {0,0,0,0,0,0,0,0,0,0};
float totalEarnings = 0;
float bills = 0;
printf("Welcome!\nThis program calculates who should pay what for the bills in a proportional manner, based upon each persons income.\nHow many people are in your household?\n\n");
do {
printf("You can enter up to 10: ");
scanf("%d", &numberOfPeople);
} while(numberOfPeople > 10);
puts("");
for(short j = 0; j < numberOfPeople; ++j){
printf("What is person %d's name? ", j+1 );
scanf(" %s", &names[j]);
}
puts("");
for(short i = 0; i < numberOfPeople; ++i){
printf("How much did %s earn this month? ", &names[i]);
scanf(" %.2f", &earnings[i]);
totalEarnings += earnings[i];
}
printf("\nTotal earnings are %.2f.\n\n", &totalEarnings);
printf("How much are the shared bills in total? ");
scanf(" %.2f", &bills);
puts("");
for(short k = 0; k < numberOfPeople; ++k){
printf("%s should pay %.2f", &names[k], &bills);
}
puts("");
return 0;
}

You have not allocated any memory to hold the names so are scanf-ing them into null.
All bets are off after this point.

You have problems with extra & characters in the printf calls, which others have noted.
The problem you are reporting is likely caused by the line:
scanf(" %.2f", &earnings[i]);
The problem is that . in scanf formats has no defined meaning (it may be being ignored, or it may be causing the scanf call to fail.) The 2 limits the input to 2 characters, so will fail if anyone has an income with more than 2 digits. So you need to get rid of those and what you REALLY need is to CHECK THE RETURN VALUE of scanf to see if it is failing and do something appropriate if it is. Something like:
while (scanf("%f", &earnings[i]) != 1) {
scanf("%*[^\n]"); /* throw away the rest of the line */
printf("That doesn't look like a number, what did they earn this month? ");
}
Something similar should be done with all the other scanf calls.

As #LoztInSpace pointed out, names is not allocated.
And another mistake is you're using & operator with %s and %f specifiers in in your printf() calls. It won't give result as expected.
Also, is your intention really a loop to ask for "number of peoples"?

Related

Getting incorrect output for a basic multiplication in my C programme

I'm new to learning C, and practicing some basic code.
I keep getting either a 0 or a very large random number for the bill multiplication at the end. I think I've narrowed it down to an issue with my "quant" value but I can't figure it out. Here's the first part of the programme (that only calculates for the pizza options so far):
#include <stdio.h>
int main()
{
int num, cho, quant, bill;
printf("Select a number from the menu:\n1. Pizza\n2. Burger\n3. Sandwiches\n4.
Beverages \n");
scanf("%d",&num);
if(num==1)
{
printf("Select a number for the food you want to order, and the quantity. \n");
printf("1. Pepperoni\t\tRs 1000 \n2. Fajita\t\tRs 1000\n3. Hot n spicy\t\tRs 1100\n4.
Chicken Tikka\tRs 1200\n");
scanf("%d,%d",&cho,&quant);
{
if(cho==1)
cho=1000;
else if(cho==2)
cho=1000;
else if(cho==3)
cho=1100;
else if(cho==4)
cho=1200;
}
bill=cho*quant;
printf("Please take your food item(s). Total bill = Rs %d \nThank you.",bill);
}
getchar();
getchar();
getchar(); getchar(); getchar();
return 0;
}
The way you have your scanf for cho and quant right now expects the user to enter two numbers separated by nothing but a comma, i.e. 2,10. If you do that format of input, your code works fine. However, if this format is broken the scanf does not properly read in a number to one or both of your variables, and they are left unitialized with potentially garbage information in them (hence the really large random numbers you're seeing).
You should probably change that line to
scanf("%d%d",&cho,&quant)

New to C; using arrays. Undesirable output

I'm new to C (programming in general). I was working on this for a while, my school assignment. I'm getting an output of many random numbers (e.g. 1xxxxxxxxx) instead of printed displays of input entered.
Here's the code in question:
#include<stdio.h>
int main()
{
char item[5][20];
double ppu[5], total, price[5], quantity[5];
int i;
for(i = 0; i < 5; i++)
{
printf("Enter item, price and quantity: ");
scanf("%s %f %f", &item[i], &ppu[i], &quantity[i]);
price[i] = ppu[i]*quantity[i];
total += price[i];
}
printf("ITEM\t\tPRICE PER UNIT\t\tQUANTITY\t\tPRICE\n");
for(i=0; i < 5; i++)
{
printf("%s\t\t%.2f\t\t%.0f\t\t%.2f\n", item[i], ppu[i], quantity[i], price[i]);
}
}
Change the format specifier to %lf. Don't forget to assign total with an initial value.
total hasn't been assigned (or initialized with) a relevant value.
Also, item[i] (a pointer to 20 chars) is converted to a pointer to char (what scanf expects) in the context of scanf. The & is wrong
scanf("%s %f %f", &item[i], &ppu[i], &quantity[i]);
// wrong ^^ ^^ ^
scanf("%s %lf %lf", item[i], &ppu[i], &quantity[i]); // thanks to Bpaul
Even better is making sure scanf did the right thing:
if (scanf("%s%lf%lf", item[i], &ppu[i], &quantity[i]) != 3) /* error */;
None of these variables and array members are initialized.
char item[5][20];
double ppu[5], total, price[5], quantity[5];
int i;
That means that they will contain random garbage values.
Now, the ones that you assign to with either scanf or the assignment operator will contain (possibly) useful data, but you are also missing out checking the return value of scanf, which will tell you how many values could be successfully read.
Also look at the way you use the 2-D array item. There is something wrong there.

Scanf repeats itself in C

This is a simple program in which the user enters a series of numbers which are then added. The result is printed on the screen. Here's the code:
int main() {
int * numbers;
int result = 0;
int howMany;
int i;
printf("How many numbers would you like to add?\n");
scanf(" %d\n", &howMany);
numbers = (int *) malloc(howMany * sizeof(int));
for(i = 0; i < howMany; i++){
printf("Please enter number %d.\n", i + 1);
scanf(" %d\n", &numbers[i]);
result = result + numbers [i];
}
printf("Result: %d", result);
return 0;
}
But there is a problem. The program asks for how many numbers the user would like to add twice for some reason. Why is that? How can I fix it?
Also, not sure if this is related but the results also make no sense. Sometimes they are correct, other times they aren't, not sure why either.
Thanks.
The program asks for how many numbers the user would like to add twice for some reason. Why is that? How can I fix it?
Your program prompts me only once for how many numbers. It does, however, defer asking for each specific number until after I enter it, and then it requires an extra non-blank line after the last (late) prompt before it outputs the result.
Also, not sure if this is related but the results also make no sense. Sometimes they are correct, other times they aren't, not sure why either.
It is related: the fact that the per-number prompts are late is confusing you about which numbers are being added.
This all comes down to your scanf() formats, as #Mark already remarked (albeit somewhat tersely). Any nonempty run of whitespace, including newlines, in a scanf() format matches a possibly-empty run of whitespace. When it is matching such a run, scanf() has to keep scanning until it sees a non-whitespace character. Interactive input is line-buffered, however, so no new input is available to it until you send a whole new line. Then the first non-whitespace character on that next line is ready and waiting for the following scanf().
scanf() can be quite tricky to use correctly, especially for interactive input. It is best suited for fixed-format input. You can do this with scanf() -- #Mark showed you how -- but the usual recommendation around here is to use fgets() to read input one line at a time, and sscanf() (or your choice of other mechanism) to parse each line. Even that can be a challenge to make bullet-proof, but you start out on firmer footing.
Your problem was because of your erroneous placement of the newline characters in your printf and scanf functions.
Here is the code you are probably looking for:
int main() {
int * numbers;
int result = 0;
int howMany;
int i;
printf("How many numbers would you like to add?: ");
scanf("%d", &howMany);
numbers = (int *) malloc(howMany * sizeof(int));
for(i = 0; i < howMany; i++){
printf("Please enter number %d: ", i + 1);
scanf("%d", &numbers[i]);
result = result + numbers [i];
}
printf("Result: %d\n", result);
return 0;
}

C: Scanf function in for loops runs one more time than it should

In the following code, I want the user to input 10 floating point numbers, and then take the average of them. However, when running it, the user is forced to input 11 numbers, but the 11th one is discarded anyway. The value of the average actually turns out to be correct. I just want to know why the scanf seems to run 1 extra time.
The problem I faced was different than that of the suggested duplicate. Here, the problem was related to my understanding of the scanf function, I actually looped the correct amount of times.
see:
#include <stdio.h>
int main (void)
{
int i;
float entry[10];
float total = 0.0;
printf("please enter 10 floating point numbers\n");
for (i = 0; i < 10; ++i)
scanf("%f\n", &entry[i]);
for (i = 0; i < 10; ++i) {
total = total + entry[i];
}
printf("The average of the 10 floating point numbers is: %f\n", total / 10);
return 0;
}
The \n in the format string is causing that.
Even after 10th element is entered, scanf waits for a non-whitespace character to be entered before it is done. After the 10 numbers have been entered, you can enter any old non-whitespace character to let scanf finish.
Remove the \n from the format string. You don't need it. Use
for (i = 0; i < 10; ++i)
scanf("%f", &entry[i]);
Remove \n inside the scanf i.e. inside the first for loop, write :
scanf("%f",&entry[i]);

C - scanf gets skipped over (even with " %d")

I am trying to figure out why I can't get this to run properly. I just want four inputs from the user, and run the calculation at the end.
#include <stdio.h>
#include <math.h>
int main(){
double amount; /* amount on deposit */
double principal; /* what's the principal */
double rate; /* annual interest rate */
int year; /* year placeholder and no. of total years */
int yearNo;
printf("What is the principal? ");
scanf("%d", &principal);
printf("What is the rate (in decimal)? ");
scanf(" .2%d", &rate);
printf("What is the principal? ");
scanf(" %d", &principal);
printf("How many years? ");
scanf(" %d\n", yearNo);
printf("%4s%21s\n", "Year", "Amount on deposit");
/* calculate the amount on deposit for each of ten years */
for (year = 1; year <= yearNo; year++){
amount = principal * pow(1.0 + rate, year);
printf("%4d%21.2f\n", year, amount);
}
return 0;
}
It properly asks for the principal and rate, but then skips over the question about Principal and asks for years. Then it just sits there waiting for a "ghost" entry?
I've been reading that the scanf() adds some whitespace when hitting enter but thought the space before the %d would fix that?
I also saw you could add do { c=getchar(); } while ( c != '\n'); after each scanf but that seems to crash the program (I added int c = 0; to the beginning too).
Thanks for any help or ideas!
EDIT:
When I change the erroneous format specifier from:
scanf(" .2%d", &rate);
to:
scanf(" %d", &rate);
I then get a crash after entering my values.
.2%d is not a valid format string.
For a start, the % has to come first. In addition, if you're after a floating point value, d is not the right character - it's for integral values.
You should be using something like %f (you don't need width or precision modifiers).
On top of that, you've made a minor mistake of not using a pointer for one of your scanf calls:
scanf(" %d\n", yearNo);
That's probably going to cause a crash, and should be changed to:
scanf(" %d\n", &yearNo);
And, as a final suggestion, it's totally unnecessary to use whitespace before (or a newline after) %d or %f family of format specifiers. The scanner automatically skips whitespace before both of those.
So, the only two scanf format strings you need in this program are "%d" and "%lf" (f is for floats, lf is for doubles).

Resources