can someone help me with my c code - c

Hello so i am creating a program that reads from a file and outputs each category of the things in the text in sorted for example i want it to output like this :
Company name: air france Date of creation: 06281957 Flight number: AT6801 Incoming city: london Arrival city: paris Amount of fuel liters left: 380 Plane category: B777
this is the input :
air qatar06281957AT680londonmadrid380B777 turkish airlines05201933TK1298istanbulmadrid250A380 lufthansa01061953LH29frankfurtmadrid75B747 air canada06281957AT7245ammanmadrid120A320 turkish airlines05201933TK1266dohamadrid522A320 air france10071933AF123parismadrid105B777 -1
The code:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main()
{
FILE *inp,*outp;
int i,j,c=0,l,c2=0,c3=0;int c4=0;int c5=0,c6=0,k,m,c7=0,flag=0;int c8=0,c9=0,c10=0,flag2=0,n,c11=0,c12=0,c13=0,c14=0,p=0,c15=0,c16=0,t,t1,t2,t3,t4,t5,t6,t7,s;
char ultimate_array[600];char plane[100][6];char date[600][6];char nflight[600][6];char destination[100][6];char fuel [100][6];char planetype [100][6];
inp=fopen("input.txt","r");
for(i=0;!feof(inp);i++)
{
fscanf(inp,"%c",&ultimate_array[i]);
}
s=strlen(ultimate_array);
for(i=0;i<s;i++)
{
printf("%c",ultimate_array[i]);
}
printf("\n\n\n\n\n\n\n\n\n\n\n\n");
for(t=0;t<6;t++)
{
for(j=0;j<200;j++)
{
c++;
if(isdigit(ultimate_array[j]))
{
c3=c;
while(c>=0)
{
plane[t][c]=ultimate_array[j];
c--; j--;
}
break;
}
}
for(k=0;k<200;k++)
{
c2++;
if(isupper(ultimate_array[k]))
{
c5=c2; c2=c2-c3; c9=c2;
while(c2>=0)
{
date[t][c2]=ultimate_array[k];
k--; c2--;
}
break;
}
}
for(l=c3;l<200;l++)
{
c4++;
if(islower(ultimate_array[l]))
{
c4=c4+c3-c5;
while(c4>=0)
{
while(flag==0)
{
c8=c4; c6=c4+c5; flag=1;
}
nflight[t][c4]=ultimate_array[l];
c4--; l--;
}
break;
}
}
c10=c9+c8;
for(m=c6;m<200;m++)
{
c7++;
if(isdigit(ultimate_array[m]))
{
c7--;m--;
while(c7>=0)
{
while(flag2==0)
{
c13=c7; flag2=1;
}
destination[t][c7]=ultimate_array[m];
c7--; m--;
}
break;
}
}
for(n=c14;n<200;n++)
{
c11++; c14=c3+c13+c10;
if(isupper(ultimate_array[n]))
{
c12=c11; c11=c11-1;
while(c11>=0)
{
fuel[t][c11]=ultimate_array[n];
c11--; n--;
}
break;
}
}
c15=c14+c12;
for(p=c15;p<200;p++)
{
c16++;
if(ultimate_array[p]=='\n')
{
while(c16>=0)
{
planetype[t][c16]=ultimate_array[p];
c16--; p--;
}
break;
}
}
for(t1=0;t1<20;t1++)
{
printf(" %c",plane[t1][t]);
}
printf("\n");
for(t2=0;t2<100;t2++)
{
printf("%c",destination[t2][t]);
}
printf("\n");
for(t3=0;t3<100;t3++)
{
printf("%c",date[t3][t]);
}
printf("\n");
for(t4=0;t4<100;t4++)
{
printf(" %c",fuel[t4][t]);
}
printf("\n");
for(t5=0;t5<100;t5++)
{
printf(" %c",nflight[t5][t]);
}
printf("\n");
for(t6=0;t6<5;t6++)
{
printf(" %c",planetype[t][t6]);
}
}
return 0;
}
I have been struggling with a lot of things but I finally managed to separate every category to a different array, however , when I tried to do it for 2D array I always get garbage can someone point out what the mistake I did ?
we couldn't read in the input file and write it in a 2D array so the concept that i have used in this code i search in the array until i find something that would help me separate the word from the others such as 06281957 in the input i used isdigit to identify which index has it then i copy the previous characters into a new array this trick seemed to work for a 1d array however when i tried to scan it to 2d it stopped working and only random chars seemed to appeari wanted to print the whole 2d array of each category but i failed to do so, for the variables i used them as checkpoints for the next check to put the things i want in a new array. For minimizing the code i cant seem to find another solution to do so i know that my code is very big but if someone has a better idea it would be awesome.

One thing that will simplify your code is using scansets. It will make it much easier to extract and separate digits from non-digits, lower from upper case. Fixed width specifiers is also a concept you should read into. To see how many characters where extracted, use %n described in previous link. Examples:
/* ... */
inp=fopen("input.txt","r");
/* your code... */
for(i=0;!feof(inp);i++)
{
fscanf(inp,"%c",&ultimate_array[i]);
}
s=strlen(ultimate_array);
for(i=0;i<s;i++)
{
printf("%c",ultimate_array[i]);
}
/* ...can be replaced by something similar to this (untested) */
fscanf(inp, "%599s%n", ultimate_array, &s); /* read up to 599 characters, put number of read characters in s */
ultimate_array[s]=0; /* set null terminator */
char a[10]; sprintf(a, "%%%ds", s); /* create print format, e.g. "%123s" */
printf(a, ultimate_array) /* print 's' number of characters */
Make sure to take it slow as the lines can be hard to read initially. As you become more familiar with it I'm sure you will find scanf does "exactly what is needed" using no loops or conditions at all.
Don't use feof. Instead check the return value from scanf. If you try extract a single "something" from file using scanf and it returns 0 (zero arguments were filled), you are done reading the file.
Making 2D arrays is almost always wrong. Group your variables in structures:
typedef struct flights_t {
char plane[100];
char date[100];
/* ... */
} flights[6]; unsigned int nrOfFlights = 0;
int c[16];
int t[7];
Make symbolic constants instead of litering the code with copies of 20, 100 and 6 all over for improved readability and maintainance. You will also recieve much better help from forums such as SO.
Your posted code is sadly beyond saving without proper description of what each code section is supposed to do. Hopefully this "answer" will get you going making better code.

Related

C linear search failing to compare two strings using strcmp, compiles fine

The program runs and exits with code 0, but gives no output, it's supposed to be a linear search program
I looked to other similar problems, i tried to end the array with \n. tried instead of just relying in just the "if (strcmp=0)" to make something with the values strcmp return, I'm very new and for what I'm learning not very good, just made things worst, i tried to look if it was about the char* values strcmp expect, but couldn't find the problem
#include <stdio.h>
#include <string.h>
#define max 15
int lineal(char elementos[], char elebus)
{
int i = 0;
for(i=0; i<max; i++)
{
if(strcmp(elementos[i], elebus)==0)
{
printf("Elemento encontrado en %d,", i); //element found in
}
else
{
printf("elemento no encontrado"); //not found
}
}
}
int main()
{
char elebus[50];
char elementos[max][50]= {"Panque", "Pastel", "Gelatina", "Leche", "Totis", "Tamarindo" "Papas", "Duraznos", "Cacahuates", "Flan", "Pan", "Yogurt", "Café", "Donas", "Waffles"};
printf("Escribir elemento a buscar\n");
scanf("%s", elebus);
int lineal(char elementos[], char elebus);
}
The expected output would be element found in "i" position, if found
if not found print "not found"
You want to pass it a string to find, not just one character Also, elementos should be a 2D array. Change the signature of your function to this:
int lineal(char elementos[max][50], char *elebus)
Also, in main, you don't call the function. Instead, you just declare it again. call it like this:
lineal(elementos, elebus);
Furthermore, I would change it to return void instead of int. You're neither returning anything (that's undefined behavior) nor are you using the return value anywhere. But I assume that this isn't the final version and you want to return the index at some point.
On a side note, right now it's printing that it didn't find the element for every time it didn't match, even if it does find it eventually. I would recommend this instead:
for (i = 0; i < max; i++)
{
if (strcmp(elementos[i], elebus) == 0)
{
printf("Elemento encontrado en %d\n,", i); //element found in
return;
}
}
printf("elemento no encontrado\n"); //not found
This is printing "elemento no encontrado" only once, and only when the string wasn't found.

Read integer untill user reaches negative integer or numbers of integer reaches upto 15

i wrote following program but it is not right. would you please assist me where i went wrong?
#include<stdio.h>
void main()
{
int count=0,a;
do
{
scanf("%d",&a);
if(a>0 )
{
for(count=0;count<15;count++);
else;
}
while(int>=0);
}
So would you tell me the correct code?
Please use building blocks of correct syntax:
main:
#include <stdio.h>
int main(void)
{
/* other code */
return 0;
}
do-while:
do
{
/* other code */
} while(count>=0);
if:
if(a>0 )
{
/* code if true */
} else
{
/* code if false */
}
for:
for(a=0;a<15;a++)
{
/* repeated code */
}
For getting input right, please read:
http://sekrit.de/webdocs/c/beginners-guide-away-from-scanf.html
How to read / parse input in C? The FAQ
When the syntax is right and the input is done correctly, then we can discuss the behaviour of your code; which I think is what you are actually asking about. Though what you are describing might already be solved/achieved once you spend some work on how to get input properly, based on the links above.

Assignment to write a program that gives the user a choice between two options - C

I have an assignment due and I am drawing a blank on what exactly to do... I'm sure it is simple but I havent quite gotten the hang of things yet. The assignment is -
Write a program that gives the user 2 menu options: either call a function that will print a greeting and your name 4 times or call a function that will count down from 10 to 0 and then print "Blastoff!". Both functions should use for loops to print the appropriate output.
I have the prompt and the functions done so far... but I am unsure of how to display one or the other depending on the choice the user makes. Thank you for your help.
#include <stdio.h>
int main (void){
// declare counter variable
int i;
// prompt the user to make a choice
printf("What would you like to do?\n 1. Print my name\n 2. Count down from 10\n");
printf("\n");
// display greeting and name 4 times
for(i=1;i<=4;i++)
{
printf("Hi, my name is Bridget\n");
}
// display countdown
for(i=10;i>=0;--i)
{
printf("%d\n", i);
}
printf("Blastoff!");
}
You should read the input from user's keyboard:
int c;
c = getchar();
if (c == '1')
{
// display greeting and name 4 times
for(i=1;i<=4;i++)
{
printf("Hi, my name is Bridget\n");
}
}
if (c == '2')
{
// display countdown
for(i=10;i>=0;--i)
{
printf("%d\n", i);
}
}
printf("Blastoff!");
you should use Switch case.
switch(choice) {
case 1: //first for loop
break;
case 2: //second for loop
break;
}
Looks like you are missing a couple of points here. Firstly, you have not yet written any functions. Try looking here to gain some insight on that front.
Secondly, to make a choice based on user input you need to actually get that input somehow. You'll probably want to use scanf.
Lastly, once you have the user's input (say, in a variable declared as int input;) you can use if to control the flow of your program based on that variable like this:
if(input == 1){
greet();
}
else {
countDown();
}
Cheers! If you have any further questions feel free to comment below.
First of all you haven't actually declared you functions. Functions in C should be declared like the main function is. For more info in this see here.
// display greeting and name 4 times
void greeting(){
for(i=1;i<=4;i++)
{
printf("Hi, my name is Bridget\n");
}
}
void countdown() {
// display countdown
for(i=10;i>=0;--i)
{
printf("%d\n", i);
}
printf("Blastoff!");
}
To get the user's input the most common way is by keyboard. scanf accomplishes that in C. Details on scanf here
int main(void){
int i, choice;
//prompt the user to make a choice
// You don't need 2 printf for the newlines stick them to one.
printf("What would you like to do?\n 1. Print my name\n 2. Count down from 10\n\n");
//This takes the user's input and puts it in the variable choice
scanf(%d, &choice);
}
Lastly to decide what to do based on the user input you can use either an if then else statement or a switch. I will provide a solution with an if statement and you can figure the one with the switch on your own. Your final code should look like this.
int main(void){
int i, choice;
//prompt the user to make a choice
// You don't need 2 printf for the newlines stick them to one.
printf("What would you like to do?\n 1. Print my name\n 2. Count down from 10\n\n");
//This takes the user's input and puts it in the variable choice
scanf(%d, &choice);
if(choice == 1){
greeting();
}else{
countdown();
}
}
// display greeting and name 4 times
void greeting(){
for(i=1;i<=4;i++)
{
printf("Hi, my name is Bridget\n");
}
}
void countdown() {
// display countdown
for(i=10;i>=0;--i)
{
printf("%d\n", i);
}
printf("Blastoff!");
}
Bear in mind that this code has a lot of flaws (error checking mainly) but I guess your assigment is not about that.
First of all you need to include libraries with function you will need. You do this by
#include <someLibrary.h>
at the beggining of you document. Libraries mostly have .h extension. Always look for them if you try to do something. You consider them to have best performance and functionality as possible (not always true).
What is next you declare your functions. Function has name, arguments which are going into it, body in which they do something and return value (can be float, int, char etc). If function doesnt return anything, they return void (dont have return at the end). You declare functions before main() with only types of arguments. Whole body is after main (it is better looking).
If you declared function with arguments, you have to provide these arguments to function in () brackets. Even if no arguments are needed, you use them like getch() in example below. Note that function become what it return. If you declared some new variables in function they will be visible only in function. On the other hand function will not see any variable from other function (main too). If you want so, declare global variables (not recommended).
#include <stdio.h>
#include <conio.h> //libraries
void function1(int);
float function2(float); //declaration of functions
int main()
{
char decision;
printf("press 'a' to run function1, press 'b' to run function2\n");
decision=getch(); //first see getch()? look in google for functionality and library !
int someInt=10;
float someFloat=11;
if(decision== 'a')
{
function1(someInt);
}
else if(decision == 'b')
{
printf("%f", funcion2(someFloat)); //example that function become what they return
}
else
{
printf("No decision has been made");
}
getch(); //program will wait for any key press
return 0;
}
void function1(int param1)
{
//print your stuff // this function return void, so doesnt have return; statement
}
float function2(float param1)
{
return 2*param1; //this function have to return some float
}

Cellular Automaton not working

I am trying to create a Cellular Automaton based on this. I have managed to do it in a simple way that would follow only rule 90 but when I changed it to accept any rule I did something wrong.
This is how the result should look.
http://natureofcode.com/book/imgs/chapter07/ch07_12.png
This is my code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *myFile = fopen ( "input.txt" , "r" );
int i, j, cell, iterations=100, current[80], previous[80], ruleCase, rule=90;
for(i=0;i<80;i++){
fscanf(myFile, "%1d", &previous[i]);
if(previous[i]==0)printf("%c",176);
else printf("%c",178);
}
for(i=0;i<=iterations;i++){
for(cell=0;cell<80;cell++)
{
if((cell>0) && (cell<79))
{
ruleCase=1*previous[cell-1]+2*previous[cell]+3*previous[cell+1];
}
else if(cell==0)
{
ruleCase=1*previous[79]+2*previous[cell]+3*previous[cell+1];
}
else if(cell==79)
{
ruleCase=1*previous[cell-1]+2*previous[cell]+3*previous[0];
}
if(rule & (128 >> ruleCase))
{
current[cell]=1;
printf("%c",178);
}
else
{
current[cell]=0;
printf("%c",176);
}
}
for(j=0;j<80;j++){
previous[j]=current[j];
}
}
return 0;
}
with the following input.txt
00000000000000000000000000000000000000100000000000000000000000000000000000000000
Thank you!
You appear to be computing ruleCase incorrectly. For example, in the general case you do ...
ruleCase=1*previous[cell-1]+2*previous[cell]+3*previous[cell+1]
... but you are trying to interpret the cell values as binary digits. Therefore, the coefficients should be powers of 2:
ruleCase=1*previous[cell-1]+2*previous[cell]+4*previous[cell+1]
Likewise for the special cases.
The fault is with this line:
ruleCase=1*previous[cell-1]+2*previous[cell]+3*previous[cell+1];
When I change the 3 to a 4 the program produces the Sierpinski triangles.
ruleCase=1*previous[cell-1]+2*previous[cell]+4*previous[cell+1];
and the other two similar lines.

One Step from Happiness --all my inputs give correct output but still it says wrong answer

I'm trying to do Timus Online Judge question #1493, "One Step from Happiness":
Vova bought a ticket in a tram of the 13th route and counted the sums of the first three and the last three digits of the ticket's number (the number has six digits). It turned out that the sums differed by one exactly. "I'm one step from happiness," Vova thought, "either the previous or the next ticket is lucky." Is he right?
Input
The input contains the number of the ticket. The number consists of six digits, some of which can be zeros. It is guaranteed that Vova counted correctly, i.e., that the sum of the first three digits differs from the sum of the last three digits by one exactly.
Output
Output "Yes" if Vova is right and "No" otherwise.
Samples
input output
--------------------
715068 Yes
445219 No
012200 Yes
Hint
All tram tickets have exactly six digits. A ticket is considered lucky if the sum of its first three digits equals the sum of its last three digits.
Here is my code in Visual C(2010) format.
#include <stdio.h>
int main()
{
int arr[5],arr1[5],arr2[5],i,a=0,b=0,n,x=0,y=0;
printf("Enter number");
scanf("%d",&n);
x=n+1;
y=n-1;
while(n>0)
{
for(i=5;i>=0;i--)
{
arr[i]=n%10;
n=n/10;
}
}
a=( arr[0]+arr[1]+arr[2]);
b=(arr[3]+arr[4]+arr[5]);
if((a-b==1)||(a-b==-1))
{
while(x>0)
{
for(i=5;i>=0;i--)
{
arr1[i]=x%10;
x=x/10;
}
}
while(y>0)
{
for(i=5;i>=0;i--)
{
arr2[i]=y%10;
y=y/10;
}
}
if ((arr1[0]+arr1[1]+arr1[2]==arr1[3]+arr1[4]+arr1[5]) ||
(arr2[0]+arr2[1]+arr2[2]==arr2[3]+arr2[4]+arr2[5]))
{ printf("Yes");}
else
{ printf("No");}
}
else
{
printf("No");
}
return 0;
}
The above code is the one I submitted and received a wrong answer in Timus Online Judge. The format in which it was submitted was Visual C (2010). I use Dev-C++ on my computer, so the code I run on my computer is the following:
#include <stdio.h>
#include <conio.h>
main()
{
int arr[5],arr1[5],arr2[5],i,a=0,b=0,n,x=0,y=0;
printf("Enter number");
scanf("%d",&n);
x=n+1;
y=n-1;
while(n>0)
{
for(i=5;i>=0;i--)
{
arr[i]=n%10;
n=n/10;
}
}
a=( arr[0]+arr[1]+arr[2]);
b=(arr[3]+arr[4]+arr[5]);
if((a-b==1)||(a-b==-1))
{
while(x>0)
{
for(i=5;i>=0;i--)
{
arr1[i]=x%10;
x=x/10;
}
}
while(y>0)
{
for(i=5;i>=0;i--)
{
arr2[i]=y%10;
y=y/10;
}
}
if ((arr1[0]+arr1[1]+arr1[2]==arr1[3]+arr1[4]+arr1[5]) ||
(arr2[0]+arr2[1]+arr2[2]==arr2[3]+arr2[4]+arr2[5]))
{ printf("Yes");}
else
{ printf("No");}
}
else
{
printf("No");
}
getch();
}
I received no compilation errors. The code ran perfectly on my Dev-C++ compiler and also gave me correct output. The problem is when I submit this code in the Visual C format and they tell me it is a wrong answer.
The exercise states:
Output "Yes" if Vova is right and "No" otherwise.
Your program prints Enter number, which the exercise does not ask for. Try to remove that.
Also, for your own and our sanity, I strongly recommend you format your program better. Finding errors is much easier in a beautiful, well-formatted program. For tips on how to make your code more readable and clean, you can head over to CodeReview.SE.

Resources