while(!feof(fp)) {
printf("\n %s %s %s", post.name, post.lastnamn, post.clubb);
for(i = 1; i <= x; i++;)
{
printf(" %d", j.number[i]);
}
fread(&post, sizeof(postTyp), 1, fp);
}
I have created two typedef struct and I am referring to them with post and j.
I have created a program that asks for a users name, last-name and clubb and stores it in a text file. I have also created a program that creates x amount of numbers in the array number[i] and save it in a text file. x counts how many times you have run a program to create an name, last-name and clubb. So if you run the program 3 times 3 numbers will be created like example down below
So when i print it i get this
Hanna Svensson FCB 1 2 3
Fabian Svensson FCB 1 2 3
Patrik Svensson FCB 1 2 3
What i want is to print it like this
Hanna Svensson FCB 1
Fabian Svensson FCB 2
Patrik Svensson FCB 3
Any tips for how I may accomplish this?
The solution is to only use the outer loop and not the inner one
i=1;
while(!feof(fp))
{
printf("\n %s %s %s", post.name, post.lastnamn, post.clubb);
printf(" %d", j.number[i]);
i++;
/* ...*/
}
Note aside: your while loop construct is very quetionable.
Related
I need to create a searching algorithm that will loop through the file, find a specific line based on input, and store it in the array.
o - after activation, the program will load the measurement module (in the format of a capital character and two
numbers), the type of the measurement quantity and lists the values sorted by time and date
measurement date and time. This command will return the list even if the 'n' command has not been activated (i.e.
dynamic fields for individual items from the input file have not yet been created).
If the file is not open (i.e. the 'v' command has not yet been executed), this option does not change anything
and prints the message Not opened file.
This is example of the text file :
9403133410
A11
R1
5.264214
1905
20220111
9403133410
A11
R1
5.264216
1905
20220112
The input :
First input: A11
Second input: R1
Output
A11 R1 1905 20220115 5.264222
My goal is to somehow store the previous line of the A11 the line 9403133410
And also store the 5.264216 1905 20220112 so the 3 lines after the R1.
This is my code :
int o_function() {
// create mer_modul_input that will take 3 characters
char mer_modul_input[4];
char typ_meranej_veliciny[3];
printf("Zadaj merany modul: \n");
scanf("%s", mer_modul_input);
printf("Zadaj typ meranej veliciny: \n");
scanf("%s", typ_meranej_veliciny);
printf("%s %s \n", mer_modul_input, typ_meranej_veliciny);
FILE *file = fopen("dataloger.txt", "r");
char c;
while ((c = fgetc(file)) != EOF) {
printf("%c", c);
}
fclose(file);
return 0;
}
If you have any ideas how to do it I really appreciate every answer Thank you have a nice day :))
This is the link to the whole project if you want to help me :
https://plum-aleda-91.tiiny.site/
So basically I want to sort number in file. so i read first
for (int i = 0; i < count; i++) {
fscanf(read_file, "%d %s %d %s\n", &custid_temp[i].id, custid_temp[i].name, &custid_temp[i].reward_point, custid_temp[i].promo);
printf("%d %s %d %s\n", custid_temp[i].id, custid_temp[i].name, custid_temp[i].reward_point, custid_temp[i].promo);
}
The File consist of this:
1 Test 200 WELCOME2017
2 James 700 WELCOME2017
See it is the points, 200 and 700 in files, I want to sort in ascending order (largest to smallest) become like this:
2 James 700 WELCOME2017
1 Test 200 WELCOME2017
So I will sort the file using this function:
for (int i = 0; i<count+1; i++)
{
for (int j = 0; j<count - i; j++)
{
if (custid[j].reward_point <custid[j + 1].reward_point)
{
struct customer temp_sort = custid[j];
custid[j] = custid[j + 1];
custid[j + 1] = temp_sort;
}
}
}
And lastly print the updated struct:
for (int i = 0; i < count; i++) {
printf("%d %s %d %s\n", custid[i].id, custid[i].name, custid[i].reward_point, custid[i].promo);
}
The result is this(VS2017):
1 Test 200 WELCOME2017
2 James 700 WELCOME2017
0 0
0 0
The result is this(CodeBlocks):
1 Test 200 WELCOME2017
2 James 700 WELCOME2017
2 James 700 WELCOME2017
1 Test 200 WELCOME2017
Process returned 2 (0x2) execution time : 0.015 s
Press any key to continue.
How come two compiler produce 2 different result, even with the same code, is there any solution for this to work on VS2017?
Thanks for the time anyway.
Try to approach the sorting problem more generally. Define an order by implementing a comparator function to be able to decide, if an element is smaller, equal or greater than another element. Define a function interface, which takes your array and a function pointer to your comparator (taking two elements of your array as parameters and returning -1, 0 or 1 for smaller, equal or greater).
Finally use quicksort or another well-known algorithm to perform the actual sorting. Decide if you require the order to be total - a property which is desirable, if your sorting algorithm is supposed to return deterministic results.
More specifically, I'd encourage the use of qsort from the C standard library. It's pretty well documented: http://www.gnu.org/software/libc/manual/html_node/Search_002fSort-Example.html
I am a super unintuitive beginner programming student working on a homework assignment. The program is to take an input table of hockey teams and game stats, calculate "points", and then output the table organized in a different way, with additional columns for points and games played.
So far, I haven't made it past scanning the input. With my while loop, I'm trying to first determine if the string is a conference name or a team name and then scan and store the subsequent table values accordingly. I'm just trying to print the same table back out at this point, but when i copy/paste the input input table which was given, I get no output, and when I manually type it in, it comes out suuper weird.
The input table looks something like this:
Conference1_Name 3 (teams in conference)
Team_1_Name 31 15 2 2 (wins, losses, ot losses, shootout losses)
Team_2_Name 24 21 1 0
Team_3_Name 27 19 0 2
Conference2_Name 4
Team_4_Name 30 15 1 1
...
aaand this is my code so far...
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
int main(void){
int n=0, N=25, nE=0, nW=0, i, w[n], l[n], otl[n], sol[n], gp[n], pts[n];
char input[30], team[n][30];
printf("Enter conference data\n");
setvbuf(stdout,NULL,_IONBF,0);
while(n<=N){
scanf("%s", input);
if (0==strcmp(input, "Eastern_Conference")) {
scanf("%d", &nE);
continue; //does not count eastern conference as a team, but stores number of teams, and does not increment n
}
if (0==strcmp(input, "Western_Conference")) {
scanf("%d", &nW);
continue; //does not count western conference as a team, but stores number of teams, and does not increment n
}
if (0==strcmp(input, "EOD")) break;
//originally i had a statement like: if (nE>0 && nW>0){N=nE+nW;) so that the loop condition n<N will break the loop on it's own but thought maybe EOD would simplify it and fix my problem//
strcpy(team[n], input);
scanf("%d%d%d%d", &w[n], &l[n], &otl[n], &sol[n]);
gp[n]=w[n]+l[n];
pts[n]=(2*w[n])+otl[n]+sol[n];
n++;
} //so we have input the data and calculated points
printf("\n%s\t%s\t%s\t%s\t%s\t%s\t%s\n", "WHL", "GP", "W", "L", "OTL", "SL", "PTS");
for(i=0; i<n; i++){
printf("%s\t%d\t%d\t%d\t%d\t%d\t%d\n", team[i], gp[i], w[i], l[i], otl[i], sol[i], pts[i]);
}
return EXIT_SUCCESS;
}
First time I have asked a question here. First here's the code:
void displayCompanyInfo(STAFF e[], int *s)
{
FILE *payRoll;
int i = 0;
int rosterNumber [100];
int count = 1;
if ((payRoll = fopen("payRoll.txt", "r")) == NULL)
{
perror ("error");
exit (0);
}
cls;
while (fgets(e[i].name, sizeof(e[i].name), payRoll) != NULL)
{
printf ("Record %i: ", count++);
printf("%s\n", e[i].name);
}
fclose(payRoll);
printf("\n\n");
pause;
cls;
} // end of display
Basically this code works. However when the text file displays it reads like this:
Record 1: Name: blah
Record 2: Age: 23
Record 3: Hourly Rate: 34
Instead I want it to read it as follows:
Record 1: Name: Blah
Age: 23
Hourly Rate: 34
Record 2: Name: Blah2
Age: 24
Hourly Rate: 35
And so on...
Any idea on how I can get this to work. I didn't post whole program because I didn't want to over do my thread. But if you need it let me know.
To this case you have to work with binary file handling.With text file it is not possible.
You have to read,write chunk of data in terms of bytes and handle it accordingly to retrieve you structure.
Say
struct e{
char name[20],
int age,
int hourly_rate
};
This structure will require
20(name) + 4(age) + 4(hourly_rate) bytes.Then you should write 28 bytes at a time in binary file and retrieve 28 bytes accordingly,which is not possible in case of text file.Because text file considers every thing as character,say age=23 it considers age field as 2 bytes and if age=3,it consider it as 1 byte.But binary file considers both thing as 4 bytes which is actual size of integer.
So the solution to your problem is binary file handling.
The problem is that the loop considers each line as a record. Instead, a record should be 3 lines. So read 3 things in the loop - add the 2 missing right before the printf.
A text file holds information about a softball team. Each line has data arranged as follows:
4 Jessie Joybat 5 2 1 1
The first item is the player's number, conveniently in the range 0–18. The second item is the player's first name, and the third is the player's last name. Each name is a single word. The next item is the player's official times at bat, followed by the number of hits, walks, and runs batted in (RBIs). The file may contain data for more than one game, so the same player may have more than one line of data, and there may be data for other players between those lines. Write a program that stores the data into an array of structures. The structure should have members to represent the first and last names, the at bats, hits, walks, and RBIs (runs batted in), and the batting average (to be calculated later). You can use the player number as an array index. The program should read to end-of-file, and it should keep cumulative totals for each player.
The world of baseball statistics is an involved one. For example, a walk or reaching base on an error doesn't count as an at-bat but could possibly produce an RBI. But all this program has to do is read and process the data file, as described next, without worrying about how realistic the data is.
The simplest way for the program to proceed is to initialize the structure contents to zeros, read the file data into temporary variables, and then add them to the contents of the corresponding structure. After the program has finished reading the file, it should then calculate the batting average for each player and store it in the corresponding structure member. The batting average is calculated by dividing the cumulative number of hits for a player by the cumulative number of at-bats; it should be a floating-point calculation. The program should then display the cumulative data for each player along with a line showing the combined statistics for the entire team.
team.txt (text file I'm working with):
4 Jessie Joybat 5 2 1 1
4 Jessie Joybat 7 3 5 3
7 Jack Donner 6 3 1 2
11 Martin Garder 4 3 2 1
15 Jaime Curtis 7 4 1 2
2 Curtis Michel 3 2 2 3
9 Gillan Morthim 9 6 6 7
12 Brett Tyler 8 7 4 3
8 Hans Gunner 7 7 2 3
14 Jessie James 11 2 3 4
12 Brett Tyler 4 3 1 3
Since I'm a beginner in C, either I misinterpreted the task from what was asked originally or it's unfairly complex (I believe the former is the case). I'm so lost that I can't think of the way how could I fill in by the criteria of index (player number) every piece of data, keep track of whether he has more than one game, calculate and fetch bat average and then print.
What I have so far is:
#define LGT 30
struct profile {
int pl_num;
char name[LGT];
char lname[LGT];
int atbat[LGT/3];
int hits[LGT/3];
int walks[LGT/3];
int runs[LGT/3];
float batavg;
};
//It's wrong obviously but it's a starting point
int main(void)
{
FILE *flx;
int i,jc,flow=0;
struct profile stat[LGT]={{0}};
if((flx=fopen("team.txt","r"))==NULL) {
fprintf(stderr,"Can't read file team!\n");
exit(1);
}
for( jc = 0; jc < 11; jc++) {
fscanf(flx,"%d",&i);
stat[i].pl_num=i;
fscanf(flx,"%s",&stat[i].name);
fscanf(flx,"%s",&stat[i].lname);
fscanf(flx,"%d",&stat[i].atbat[flow]);
fscanf(flx,"%d",&stat[i].hits[flow]);
fscanf(flx,"%d",&stat[i].walks[flow]);
fscanf(flx,"%d",&stat[i].runs[flow]);
flow++;
}
}
Advice 1: don't declare arrays like atbat[LGT/3].
Advice 2: Instead of multiple fscanf you could read the whole line in a shot.
Advice 3: Since the number of players is limited and the player number has a good range (0-18), using that player number as an index into the struct array is a good idea.
Advice 4: Since you need cumulative data for each player (no need to store his history points), then you don't need arrays of integers, just an integer to represent the total.
So:
#include <stdio.h>
#define PLAYERS_NO 19
typedef struct
{
char name[20+1];
char lastName[25+1];
int atbat;
int hits;
int walks;
int runs;
float batavg;
} Profile;
int main(int argc, char** argv)
{
Profile stats[PLAYERS_NO];
int i;
FILE* dataFile;
int playerNo;
Profile tmpProfile;
int games = 0;
for(i=0; i<PLAYERS_NO; ++i)
{
stats[i].name[0] = '\0';
stats[i].lastName[0] = '\0';
stats[i].atbat = 0;
stats[i].hits = 0;
stats[i].walks = 0;
stats[i].runs = 0;
}
dataFile = fopen("team.txt", "r");
if ( dataFile == NULL )
{
fprintf(stderr, "Can't read file team!\n");
exit(1);
}
for(i=0; i<PLAYERS_NO && !feof(dataFile); ++i, ++games)
{
fscanf(dataFile, "%d", &playerNo);
if ( playerNo <0 || playerNo > PLAYERS_NO )
{
fprintf(stderr, "Player number out of range\n");
continue;
}
fscanf(dataFile, "%s %s %d %d %d %d",
&tmpProfile.name,
&tmpProfile.lastName,
&tmpProfile.atbat,
&tmpProfile.hits,
&tmpProfile.walks,
&tmpProfile.runs);
printf("READ: %d %s %s %d %d %d %d\n",
playerNo,
tmpProfile.name,
tmpProfile.lastName,
tmpProfile.atbat,
tmpProfile.hits,
tmpProfile.walks,
tmpProfile.runs);
strcpy(stats[playerNo].name, tmpProfile.name);
strcpy(stats[playerNo].lastName, tmpProfile.lastName);
stats[playerNo].atbat += tmpProfile.atbat;
stats[playerNo].hits += tmpProfile.hits;
stats[playerNo].walks += tmpProfile.walks;
stats[playerNo].runs += tmpProfile.runs;
}
/* exercise: compute the average */
fclose(dataFile);
for(i=0; i<PLAYERS_NO; ++i)
{
if ( stats[i].name[0] == '\0' )
continue;
printf("%d %s %s %d %d %d %d\n",
i,
stats[i].name,
stats[i].lastName,
stats[i].atbat,
stats[i].hits,
stats[i].walks,
stats[i].runs);
}
return 0;
}
The first rule of programming: Divide and conquer.
So you need to identify individual operations. One such operation is "load one row of input", another is "look up a player". If you have some of those operations (more will come up as you go), you can start building your program:
while( more_input ) {
row = load_one_row()
player = find_player( row.name )
if( !player ) {
player = create_player( row.name )
add_player( player )
}
... do something with row and player ...
}
when you have that, you can start to write all the functions.
An important point here is to write test cases. Start with a simple input and test the code to read a row. Do you get the correct results?
If so, test the code to find/create players.
The test cases make sure that you can forget about code that already works.
Use a framework like Check for this.
If I were doing this, I'd start with a structure that only held one "set" of data, then create an array of those structs:
struct profile {
char name[NAMELEN];
char lname[NAMELEN];
int atbat;
int hits;
int walks;
int runs;
float batavg;
};
Since you're using the player's number as the index into an array, you don't need to store it into the structure too.
I think that will simplify the problem a little bit. You don't need to store multiple data items for a single player -- when you get a duplicate, you just ignore some of the new data (like the names, which should be identical) and sum up the others (e.g., at-bats, hits).