Segmentation Fault: 11 & illegal character encoding in string literal - c

The illegal character error is coming from my print function in my else statement. And when I try and run the file, I receive a segmentation fault:11. The goal of this program is to enter a lowerbound temperature from 0-80 and a upper bound temperature greater than the lowerbound but less than 90. As well as a percentage of days needed in the range.
#include <stdio.h>
int main(){
// Enter information in regards to your city
int percentage_range;
double low_bound, upper_bound, temperature;
printf("Please enter the lower temperature bound in Fahrenheit.\n");
scanf("%lf", &low_bound);
printf("Please enter the upper temperature bound in Fahrenheit.\n");
scanf("%lf", &upper_bound);
printf("Please enter the percentage of days needed in the range.\n");
scanf("%d", &percentage_range);
// Read in the file name
char filename[20];
printf("Please enter the name of your weather data file for your city.\n");
scanf("%s", filename);
// Open the file
FILE* ifp = fopen(filename, "r");
int month, day, year;
fscanf(ifp, "%d", &month);
// looping totals
double sum = 0;
double sum_range = 0;
int numdays = 0;
int num_totaldays = 0;
double percentage;
while (month != -1){
num_totaldays++;
// Read in the rest of the file line
fscanf(ifp, "%d,%d,%lf",&day, &year, &temperature);
while (low_bound <= upper_bound){
sum = sum + temperature;
numdays++;
percentage = sum/numdays;
printf("Days in between %lf and %lf degrees:%d", low_bound, upper_bound, numdays);
printf("Total number of days:%d",num_totaldays );
printf("Percentage of days in range:%lf",percentage);
// if the percentage is in range
if (percentage >= percentage_range){
printf("Great, I recommend opening a Pizza Shack at your location!\n");
}
// if not print this
else
printf("Sorry, your weather isn’t temperate enough for Pizza Shack.");
}
}
//close file
fclose(ifp);
return 0;
}

Replace the "isn’t" with "isn't". The apostrophe character you are using is weird.

Related

Program is not printing completely

I'm trying programming 1st time and not getting the output of this program.Though it looks simple but the code doesn't prints after taking the input like name, roll, marks obtained by student.
I have attached the screenshot of compiler.
Thank you!
#include<stdio.h>
int main()
{
int roll,phy,che,ca,total;
float percentage;
char name[20];
printf("enter the name of student: "); //studentname
scanf("%s",&name);
printf("enter the roll number: "); //roll number
scanf("%d",&roll);
printf("enter the marks obtained in phy,che,ca: "); //marks obtained/subject
scanf("%d%d%d ",&phy,&che,&ca);
//doesnt works from here.
total= (phy+che+ca); //calculating total marks
printf("the total marks obtained is %d\n",total);
percentage =total/3.0; //calculating percentage student got.
printf("the total percentage obtained is %d\n",percentage);
if(percentage>=80)
printf("first division\n"); //first division
else if(percentage>=60 && percentage<=80)
printf("second division\n"); //second division
else if(percentage>=60)
printf("third divison\n"); //third division
else if(percentage>=10)
printf("you failed!\n"); //failed
else
printf("invalid input\n"); //invalid input
return 0;
}
screenshot of the compiler
scanf("%d%d%d ",&phy,&che,&ca);
There is an extra blank character in format. So you should input a more character after you input 3 integers.
And you shouldn't use %d to print a float type variable, you should use %f.

C loop with undetermined number

I've been stumped for the past few days trying to modify my current code to be able to input an undetermined number of students.
#include <stdio.h>
int main(void)
{
char StudentName[100];
float ExamValue, Sum, Avg;
int students, exams;
for (students = 0; students < 5; students++)
{
Sum = 0.0;
printf("Enter Student Name \n");
scanf("%s", StudentName);
for (exams = 0; exams < 3; exams++)
{
printf ("Enter exam grade: \n");
scanf("%f", &ExamValue);
Sum += ExamValue;
}
Avg = Sum / 3.0;
printf("Average for %s is %f\n", StudentName, Avg);
}
return 0;
}
As it is now, I have to manually input the amount of students. Does anyone know how I can modify this code in order to enter an undetermined amount of students? I'm starting to think that it is impossible to do and maintain the integrity of the rest of the code. Any help is greatly appreciated, thanks!
You can do something like while (stillAdding) instead of the for loop, and prompt the user with Enter student name or QUIT to stop, or even Would you like to enter a new student [Y/n]. You'd modify the stillAdding variable accordingly. In short, you leave it up to the user to specify when they want to stop inputting more data.
You can ask for the number of users before the for and then use that number as upper bounds of the for. Something like this:
int students, exams, nr;
printf("Enter Student Number \n");
scanf("%d", &nr);
for (students = 0; students < nr; students++)
{
//your code
}
You can ask the user whether there are more students per loop:
#include <stdio.h>
int main(void)
{
char StudentName[100];
float ExamValue, Sum, Avg;
int students, exams;
char stop;
for (;;)
{
Sum = 0.0;
printf("Enter Student Name \n");
scanf(" %s", StudentName);
for (exams = 0; exams < 3; exams++)
{
printf ("Enter exam grade: \n");
scanf("%f", &ExamValue);
Sum += ExamValue;
}
Avg = Sum / 3.0;
printf("Average for %s is %f\n", StudentName, Avg);
puts("More students?(Y/N)");
scanf("%*[^yYnN]%c%*[^\n]%*c", &stop); // read one of 'y', 'Y', 'n', 'N', then discard that line, including '\n'.
if (stop == 'N' || stop == 'n')
break;
}
return 0;
}
You can prompt the user to supply the number of inputs. Once the user tells you how many inputs will be given, then you can simply use a for loop to read that many inputs

for/while loop memory clearing in C

In my program I'm messing around with, it simply asks for how many tests one has written and then returns an average. However I've modified it a bit so that it asks if the marks entered are correct.
Problem 1: It doesn't let you input your marks for all your tests
Problem 2: If the marks are wrong it starts over but keep the previous inputs in it's memory? How do I fix the?
Here's the code:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
//int variables for grade
unsigned int counter; //number of grades to be entered next
int grade;
int total;
float average;
// user input
int userInput; // amount of tests
int yesNo;
//amount of test passed
unsigned int pass = 0;
unsigned int fail = 0;
int doCount = 1;
//unsigned int test;
//---------------------------------------------------------------------------------------------------//
//standards for program to abide to
total = 0; //Total amount of test to be set to zero, until while statement
counter = 1; //Loop counter to start from one
//---------------------------------------------------------------------------------------------------//
printf ("Please enter amount of test you've written so far: ");
scanf ("%d", &userInput);
//printf ("%d", userInput);
//---------------------------------------------------------------------------------------------------//
do {
//Body of calculations of program
for(counter = 0; counter <= userInput; ++counter) { //for loop that correlates to userInput for amount of passes and test marks
printf ("Please enter percentage mark: "); //prompt for test mark
scanf("%d", &grade);
total = total + grade;
counter = counter + 1;
if (grade >= 40) { //if statement for pass or fail
pass = pass + 1;
} else {
fail = fail + 1;
}
}//end of for loop
printf ("Are the grades entered correct? (1 = yes, 2 = no): "); // user input for yesNo - are inputs correct
scanf ("%d", &yesNo);
if (yesNo == 2) {
} else {
average = ((float)total / userInput); //Getting average for tests so far
//if statement to clarify if you're passing
if (average < 40) {
printf ("\nYou are below sub minimum!\n");
printf ("Your overall average is: %.2f %\n", average);
printf ("Passed: %d\n", pass);
printf ("Failed: %d", fail);
} else if (average >= 75){
printf ("\nYou have a distinction agregate!\n");
printf ("Your overall average is: %.2f %\n", average);
printf ("Passed: %d\n", pass);
printf ("Failed: %d", fail);
} else {
printf ("\nYour overall average is: %.2f %\n", average);
printf ("Passed: %d\n", pass);
printf ("Failed: %d", fail);
}
doCount = 2;
}
} while (doCount == 1);
average = ((float)total / userInput); //Getting average for tests so far
//---------------------------------------------------------------------------------------------------//
getch ();
return 0;
}
In your do while loop, when you come around for your second pass you need to reset your variables. Specifically the total variable should be reset to zero. You do it for the first time outside the do while loop but once it's in the loop for the second pass it doesn't get reset to 0.
As for not reading all test inputs, if it asks for 9 but you need 10 then it likely is a problem with the for loop. I typically use counter++ and not ++counter as it increments the counter after the operation and not before the operation. That may or may not be the reason as I did not run your code, but it is worth looking at.
I've edited your code and commented the changes:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
//int variables for grade
unsigned int counter; //number of grades to be entered next
int grade;
int total;
float average;
// user input
int userInput; // amount of tests
int yesNo;
//amount of test passed
unsigned int pass = 0;
unsigned int fail = 0;
int doCount = 1;
//unsigned int test;
//---------------------------------------------------------------------------------------------------//
//standards for program to abide to
total = 0; //Total amount of test to be set to zero, until while statement
counter = 0; //Loop counter to start from zero, It's always better to start from zero
//---------------------------------------------------------------------------------------------------//
printf("Please enter amount of test you've written so far: ");
scanf("%d", &userInput);
//printf ("%d", userInput);
//---------------------------------------------------------------------------------------------------//
do {
//Body of calculations of program
total = 0; //You need to reset total pass and fail
pass = 0;
fail = 0;
for (counter = 0; counter < userInput; ++counter) { //for loop that correlates to userInput for amount of passes and test marks
printf("Please enter percentage mark: "); //prompt for test mark
scanf("%d", &grade);
total = total + grade;
//counter = counter + 1; You DON't need that
if (grade >= 40) { //if statement for pass or fail
pass = pass + 1;
}
else {
fail = fail + 1;
}
}//end of for loop
printf("Are the grades entered correct? (1 = yes, 2 = no): "); // user input for yesNo - are inputs correct
scanf("%d", &yesNo);
if (yesNo == 2) {
}
else {
average = ((float)total / userInput); //Getting average for tests so far
//if statement to clarify if you're passing
if (average < 40) {
printf("\nYou are below sub minimum!\n");
printf("Your overall average is: %.2f %\n", average);
printf("Passed: %d\n", pass);
printf("Failed: %d", fail);
}
else if (average >= 75) {
printf("\nYou have a distinction agregate!\n");
printf("Your overall average is: %.2f %\n", average);
printf("Passed: %d\n", pass);
printf("Failed: %d", fail);
}
else {
printf("\nYour overall average is: %.2f %\n", average);
printf("Passed: %d\n", pass);
printf("Failed: %d", fail);
}
doCount = 2;
}
} while (doCount == 1);
average = ((float)total / userInput); //Getting average for tests so far
//---------------------------------------------------------------------------------------------------//
getch();
return 0;
}

Loop with rolling total in c

I am trying to get a c program to ask me how many items i am buying than to ask the price for each item while keeping a rolling total and than ask again in a loop. I have the loop working fine but am having problems getting it to give me proper output.
here is the output i am getting when i run it.
http://i119.photobucket.com/albums/o134/halodude808/assignment2_zpsd46e84b8.jpg
#include <stdio.h>
#include <math.h>
int main(void)
{
//variables used
float penny = .01;
float nickel = .05;
float dime = .1;
float quarter = .25;
int items = 0;
float paid= 0.0;
float total = 0.0;
float price =0.0;
int counter =0.0;
for (;;)
{
printf("Please enter the number of grocery items:");
scanf("%d", &items);
for (counter = 1; counter <= items; counter++)
{
printf("Please enter the price for item #%d:", counter);
scanf("%f", &price);
total += price;
}
printf("items = %d total = %f \n", &items, &total);
getchar();
getchar();
}
}
Change
printf("items = %f total = %f \n", &items, &total);
to
printf("items = %i total = %f \n", items, total);
Also, you might want to consider checking for invalid values (zeroes, negative, characters, etc).

How do I only accept numbers in C and block the user from entering letters and special characters?

I just need to figure out how to give an error is the user enters anything that is not number. I already set the values of the code that cannot be passed or be gone under.
I just need to only accept numbers: if a letter or any type of special character is entered I want the program to just cancel itself. How can I do this?
#include <stdio.h>
#include <math.h>
int main(void) {
float base, height;
float area;
printf("Please enter the value of base of the triangle: \n");
scanf ("%f", &base);
if(base<.5)
printf("Invalid Input\n");
while (base<.5)
return 0;
if(base>100)
printf("Invalid Input\n");
while(base>100)
return 0;
printf("Please enter the value of height of the triangle:\n");
scanf("%f", &height);
if(height<1)
printf("Invalid Input\n");
while(height<1)
return 0;
if(height>75)
printf("Invalid Input\n");
while (height>75)
return 0;
area = base * height/2;
printf("The area of the triangle for base: %f and height: %f is %f \n", base,
height , area );
return 0;
}
You cannot block the user from entering whatever he or she wants, but you can use the return value of scanf to decide if a valid value has been entered, and prompt the user for a correct input:
float base;
do {
printf("Please enter the value of base of the triangle: \n");
} while (scanf ("%f", &base) != 1 || base < .5 || base > 100);
This loop will continue until all three conditions are met:
scanf has returned exactly one item,
The value provided by scanf is greater than or equal to 0.5, and
The value provided by scanf is less than or equal to 100
scanf returns the number of variables that have been matched and filled with values succesfully.
just do:
int result = scanf ("%f", &base);
if(result != 1)
{
...//handle error
}
I think that you could read the input character by character and then check if it's a number and if it isn't you show your error message.
#include <stdio.h>
#include <math.h>
int main(void)
{
float base, height;
float area;
printf("Please enter the value of base of the triangle: \n");
char c='\n';
char success=0;
base=0;
char dot=0;
do{
scanf ("%c", &c);
if((c>=48)&&(c<=57)){
if(dot==0)
base=base*10+(c-48);
else{
base+=(c-48)/dot;
dot*=10;
}
}
else
if((c=='.')&&(dot==0))
dot=10;
else
if(c!='\n')
success=1;
}while((c!='\n')&&(succes==0));
if(success!=0) return -1; //error we break out
if(base<.5)
printf("Invalid Input\n");
while (base<.5)
return 0;
if(base>100)
printf("Invalid Input\n");
while(base>100)
return 0;
printf("Please enter the value of height of the triangle:\n");
c='\n';
success=0;
height=0;
dot=0;
do{
scanf ("%c", &c);
if((c>=48)&&(c<=57)){
if(dot==0)
height=height*10+(c-48);
else{
height+=(c-48)/dot;
dot*=10;
}
}
else
if((c=='.')&&(dot==0))//check if is the first time the user insert a dot
dot=10;
else
if(c!='\n')
success=1;
}while((c!='\n')&&(succes==0));
if(success!=0) return -1; //error we break out
if(height<1)
printf("Invalid Input\n");
while(height<1)
return 0;
if(height>75)
printf("Invalid Input\n");
while (height>75)
return 0;
area = base * height/2;
printf("The area of the triangle for base: %f and height: %f is %f \n", base,
height , area );
return 0;
}

Resources