probably another dumb error but I really can't wrap my head around this.
I'm writing a basic polynomials class, and my program suddenly crashes upon input of a couple of ints.. I tried searching for a solution but I couldn't find one :/
The code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "Homework.h"
#include "Fraction.h"
int main()
{
//Input from user
int degree, i;
printf("Insert the degree of the polynomomial: \n");
scanf("%d", °ree);
//Get the coefficcients
struct fraction *bucket = malloc((sizeof(struct fraction))*(degree + 1));
int num;
unsigned int den;
for(i = 0; i < degree + 1; i++)
{
num = 0;
den = 1;
printf("Insert the coefficcient of degree %d, first num and afterwards
the den \n", i);
printf("Numerator:\n");
if(scanf("%d", &num) != 1)
printf("Input error\n");
printf("Denominator:\n");
if(scanf("%u", &den) != 1)
printf("Input error\n");
//struct fraction temp = {num, den};
//memcpy(&bucket[0], &temp, sizeof(struct fraction));
}
//Check insertion
printf("Test\n");
//print_fraction(bucket[0]);
}
The program exits even before printing "Test", and to input I am using input number + enter key.
Thanks very much for any help!
Proof it compiles
Your code seems to be working fine.
The only changes i've made in order to compile it was to comment out the line where you are using malloc, and also brought your print statement on one line.
If you are using a newer version of Visual Studio then it will give you issues when using the scanf function. You either have to use scanf_s or disable the warning with this line at the top:
#pragma warning(disable: 4996)
Hope this helps.
Related
I apologize if the title is misleading in anyway, because I don't know where or how to start on this one.
Recently I wrote a math game that makes random numbers and turns them into equations. But all the program can do Is take in numbers, if I wanted to allow commands like say show-stats to show your stats. I have to write the command and then a number after for the command to get recognized like so
show-stats 0
score is 1
show-stats
0 //number is required for some reason
score is 1
This is a minimal example I wrote
#include <stdio.h>
#include <string.h>
int main() {
int bar;
char foo[]="";
int score = 1;
scanf("%s%i",foo,&bar);
if(strcmp(foo,"show-stats"))
{
printf("Score is %i",score);
}
if(bar == 2)
{
score = bar*2;
printf("Doubled Points.\n");
}
}
Here is the actual code, In case you need. Also, I'd like advisors on the actual code, like if its spaghetti or if something is performance consuming, or just what I can improve on in general if its not too much trouble. thanks in advance and I'm open to suggestions.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#define VER 10
#define DIV "-----"
int main()
{
system("clear");
unsigned int x,y; //equation numbers
int ans,sum; //user answer
unsigned int max = 10; //max possible number that can be made, cannot go under 10.
int score; //what do you think?
char operation;
int correctAnswers = 0,wrongAnswers = 0;
printf("Math game\nVersion %i.\n",VER);
for (; ;)
{
//phase 1; make numbers.
srand(time(NULL));
x = rand() % max;
y = rand() % max;
//phase 2; make operation type.
operation = rand() % 2;
switch (operation)
{
case 0:operation = '+';sum = x + y;break;
case 1:operation = '-';sum = x - y;break;
}
//phase 3; write question to console and get user answer
printf("What is %i %c %i? ",x,operation,y); //get input
scanf("%i",&ans);
//phase 4; determine right answer
if (ans == sum)
{
score++;
correctAnswers++;
max++;
printf("Your correct! +1!\n");
printf("%sStats%s\nScore:%i\nMax possible number:%i\nCorrect Answers:%i\nWrong Answers:%i\n%s%s%s\n",DIV,DIV,score,max,correctAnswers,wrongAnswers,DIV,DIV,DIV); //print stats when user wins,is a seperate call for readability. same thing on line 53 but for loss
}
else
{
score--;
wrongAnswers++;
if(max>10){max--;}; //assures max doesn't go under 10
printf("Wrong! -1\n");
printf("%sStats%s\nThe correct answer was %i\nMax possible number : %i\nScore : %i\nCorrect Answers : %i\nWrong Answers : %i\n%s%s%s\n",DIV,DIV,sum,max,score,correctAnswers,wrongAnswers,DIV,DIV,DIV);
}
}
}
Thanks to DevSolar, I know how to do this. Using fgets() and strtol() you can collect the entire string, and parse it into the command and the number, I read up on strtol here https://www.tutorialspoint.com/c_standard_library/c_function_strtol.htm
edit:
char str[30] = ""; //the string the user types
fgets(str,30,stdin);
char *ptr; //the part of the string turned into words
long ret; //the part of the string turned into numbers
ret = strtol(str, &ptr, 10); //parameter 1;source string that is parsed;//parameter 2; string part of source.//parameter 3; base
printf("The number(unsigned long integer) is %ld\n", ret);
printf("String part is |%s|", ptr);
I've trying to do it for about an hour, but I can't seem to get it right. How is it done?
The code I have at the moment is:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(){
int j=-1;
while(j<0){
printf("Enter a number: \n");
scanf("%d", &j);
}
int i=j;
for(i=j; i<=100; i++){
printf("%d \n", i);
}
return 0;
}
The original specification (before code was added) was a little vague but, in terms of the process to follow, that's irrelevant. Let's assume they're as follows:
get two numbers from the user.
if their product is greater than a thousand, print it and stop.
otherwise, print product and go back to first bullet point.
(if that's not quite what you're after, the process is still the same, you just have to adjust the individual steps).
Translating that in to pseudo-code is often a first good step when developing. That would give you something like:
def program:
set product to -1
while product <= 1000:
print prompt asking for numbers
get num1 and num2 from user
set product to num1 * num2
print product
print "target reached"
From that point, it's a matter of converting the pseudo-code into a formal computer language, which is generally close to a one-to-one mapping operation.
A good first attempt would be along the lines of:
#include <stdio.h>
int main (void) {
int num1, num2, product = -1;
while (product < 1000) {
printf ("Please enter two whole numbers, separated by a space: ");
scanf ("%d %d", &num1, &num2);
product = num1 * num2;
printf ("Product is %d\n", product);
}
puts ("Target reached");
return 0;
}
although there will no doubt be problems with this since it doesn't robustly handle invalid input. However, at the level you're operating, it would be a good start.
In terms of the code you've supplied (which probably should have been in the original question, though I've added it now):
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(){
int j=-1;
while(j<0){
printf("Enter a number: \n");
scanf("%d", &j);
}
int i=j;
for(i=j; i<=100; i++){
printf("%d \n", i);
}
return 0;
}
a better way to do the final loop would be along the lines of:
int i = 1;
while (i < 1000) {
i = i * j;
printf ("%n\n", i);
}
This uses the correct terminating condition of the multiplied number being a thousand or more rather than what you had, a fixed number of multiplications.
You may also want to catch the possibility that the user enters one, which would result in an infinite loop.
A (relatively) professional program to do this would be similar to:
#include <stdio.h>
int main (void) {
// Get starting point, two or more.
int start = 0;
while (start < 2) {
printf("Enter a number greater than one: ");
if (scanf("%d", &start) != 1) {
// No integer available, clear to end of input line.
for (int ch = 0; ch != '\n'; ch = getchar());
}
}
// Start with one, continue while less than a thousand.
int curr = 1;
while (curr < 1000) {
// Multiply then print.
curr *= start;
printf ("%d\n", curr);
}
return 0;
}
This has the following features:
more suitable variable names.
detection and repair of most invalid input.
comments.
That code is included just as an educational example showing how to do a reasonably good job. If you use it as-is for your classwork, don't be surprised if your educators fail you for plagiarism. I'm pretty certain most of them would be using web-search tools to detect that sort of stuff.
I'm not 100% clear on what you are asking for so I'm assuming the following that you want to get user to keep on entering numbers (I've assumed positive integers) until the all of them multiplied together is greater than or equal to 1000).
The code here starts with the value 1 (because starting with 0 will mean it will never get to anything other than 0) and multiples positive integers to it while the product of all of them remains under 1000. Finally it prints the total (which may be over 1000) and also the number of values entered by the user.
I hope this helps.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char input[10];
unsigned currentTotal = 1;
unsigned value;
unsigned numEntered = 0;
while( currentTotal < 1000 )
{
printf( "Enter a number: \n" );
fgets( input, sizeof(input), stdin );
value = atoi( input );
if( value > 0 )
{
currentTotal *= value;
numEntered += 1;
}
else
{
printf( "Please enter a positive integer value\n" );
}
}
printf( "You entered %u numbers which when multiplied together equal %u\n", numEntered, currentTotal );
return 0;
}
Try this one:
#include <stdio.h>
int main()
{
int input,output=1;
while(1)
{
scanf("%d",&input);
if(input<=0)
printf("Please enter a positive integer not less than 1 :\n");
else if(input>0)
output*=input;
if(output>1000)
{
printf("\nThe result is: %d",output);
break;
}
}
return 0;
}
Hello I am new to C and trying to make a program that asks for the user to input a whole bunch of numbers. I want to loop scanf so that it keeps asking and when the user inputs "0", it stops, reads off the even and odd numbers inputted, and counts them seperatly. Right now I have it to keep asking for new numbers after user presses "Enter" but when i type "0" is just keeps asking for more numbers and doesn't stop. What am I doing wrong? Like I said before, I am very new so baby words are best.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main (void) {
int number_of_integers, sum = 0, i, integer;
char user_name[128];
printf("What is your name?\n");
scanf("%s", user_name);
printf("\nEnter any real numbers followed by ENTER.\n");
while (integer != 0) {
scanf("%s", &integer);
if (integer == 0)
break;
}
printf("%s, the numbers you entered are broken down as follows:\n", user_name);
return 0;
}
As a commenter indicated, we aren't a homework or tutoring service, but I'm doing you a favor by producing an actual working example that I just made up. It's up to you now to tailor it exactly to your needs.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main (void) {
int max=100;
int integer;
int even[max];
int odd[max];
int index=0;
int evencount=0;
int oddcount=0;
char user_name[128];
printf("What is your name?\n");
scanf("%s", user_name);
printf("\nEnter any real numbers followed by ENTER.\n");
while (index < max){
scanf("%d", &integer);
if (integer == 0)
break;
if ((integer % 2) == 0){
evencount++;
even[evencount]=integer;
}else{
oddcount++;
odd[oddcount]=integer;
}
index++;
}
printf("%s, the %d numbers you entered are broken down as follows:\n", user_name,index);
printf("%d odd integer(s):\n",oddcount);
while (oddcount > 0){
printf("%d\n",odd[oddcount]);
oddcount--;
}
printf("%d even integer(s):\n",evencount);
while (evencount > 0){
printf("%d\n",even[evencount]);
evencount--;
}
return 0;
}
for our homework we have to compile the program we wrote in the school. I have typed it without mistakes(verified with my colleagues) and the program does not work, I am using DEV C++ and the error log says, file not recognized: File format not recognized.
I tried using integer and not double but it stays the same...I have no idea what is wrong.
#include <stdio.h>
#define VELIKOST 23
int main (void)
{
double dPolje[VELIKOST];
int iStevec,iVecje=0;
printf("Algoritem, ki določi koliko elementov podatkovnega polja imajo vrednosti vecje ali enake od 10 \r\n");
for(iStevec=0;iStevec<VELIKOST;iStevec++)
{
printf("Vnesite %i. stevilo:",iStevec=iStevec+1);
fflush(stdin);
scanf("%lf",&dPolje[iStevec]);
if(dPolje[VELIKOST]>=10)
{
iVecje++;
printf("Element dPolje [%i]=%f.",iStevec,dPolje[iStevec]);
}
printf("%i elementov polja je imelo vecje ali enako vredost 10.",iVecje);
return(0);
}
}
I'm guessing that Dev C++ doesn't support Slovenian.
Create a new file and try this code:
#include <stdio.h>
#define SIZE 23
int main(){
double dField[SIZE];
int i, larger = 0;
printf("This algorithm, determines how many data field items have values greater than or equal to 10.\n");
for (i = 0; i < SIZE; i++){
printf("Enter field number %i:", i + 1); //Note I fixed this original code had i = i + 1
//fflush(stdin); unneeded
scanf("%lf", &dField[i]);
if (dField[i] >= 10){
larger++;
printf("Field number %i = %lf", i, dField[i]);
}
} //Moved this above final output and return
printf("%i field items were greater than or equal to 10 ", larger);
return 0;
}
I expect that to work.
Either way I'd definitely change compilers. Visual Studio Community Is a great fully featured IDE.
I'm relatively new to C programming, its my 6th week in class so far i haven't had any major issues. I just cant figure out were i'm going wrong with my current assignment and its due in just a couple hours. Here is what i have so far. i'm using visual studio 2012.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char textChar;
int textLenght = 0;
int asciiArray[128] = {0};
int i;
int main()
{
printf("Enter a line of text: ");
scanf("%d", &textChar);
while ((textChar = getchar())!= '\n') {
textLenght++;
asciiArray[textChar]++;
}
printf("\nFREQUENCY TABLE\n");
printf("---------------\n");
printf("Char Count %% of Total\n");
printf("---- ----- ----------\n");
printf(" ALL %5d %9.2f%%\n", textLenght,( textLenght * 100.0 ) / textLenght );
for (i = 0; i < 128; i++)
if( asciiArray[textChar] != 0 )
printf("%c %d %9.2f%% \n",i+ "0",asciiArray[textChar]);
getchar();
getchar();
return 0;
}
Now i know there is a problem within my for loop because its not displaying, I'm just not sure if there are other problems besides that. Any help is greatly appreciated thanks in advance.
This line is not right.
scanf("%d", &textChar);
It's not clear to me what you are trying to accomplish with this line.
When you use %d as the format specifier, the function will try to read an integer and store it at the given address. Since type of textChar is not int, you are going to run into undefined behavior right away.
Instead of using getchar, which is not a standard C library function, you should use fgetc(stdin).
fgetc() returns an int. Make sure to change the type of textChar to int.
Change the lines:
printf("Enter a line of text: ");
scanf("%d", &textChar);
while ((textChar = getchar())!= '\n') {
textLenght++;
asciiArray[textChar]++;
}
to
printf("Enter a line of text: ");
while ((textChar = fgetc(stdin))!= '\n') {
textLenght++;
asciiArray[textChar]++;
}
I would remove the last two calls to getchar(). They don't seem to serve any purpose.