Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
How would I read information from a file to variables if I don't know how long it's gonna be.
Example of file:
student name
class grade credits
class grade credits
class grade credits
How would I save this info from this file if the number of classes varied. I need to print this information to the screen, while using the grades and number of credits to calculate a students GPA.
As proposed by fluter, fgets will allow you read the file line by line. getline is another (better IMHO) solution, it's manpage provides a simple usage example.
Then inside the reading loop, you have several options. I suggest you sscanf applied on the line read.
It returns the number of items read. In this kind of simple case, I usually try to scan the line with different format strings and check the number of items read to verify if the line matched.
For example, you could use something like:
"%s" as the format string for student name lines
"%s %c %d" as the format string for grade lines
And I suggest you to compute the GPA inside the loop, this way, you shouldn't have to store the grades, if I'm correct.
The usual way to do is to scan the input file until it meet the end of file or EOF, so you know you have reached the end of the file.
Something like this:
FILE *fp = fopen("grade.txt", "r");
if (!fp) { exit(1); }
char line[1024];
char name[1024];
char *s;
s = fgets(line, sizeof line, fp);
if (!s) { fclose(fp); exit(0); }
strcpy(name, line);
do {
s = fgets(line, sizeof line, fp);
// convert line to grade, to integer or double as you want
} while (s != NULL);
// compute the GPA
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
#include<stdio.h>
int main()
{
char word[1000];
scanf("word%s", word);
printf("%s", word);
}
It seems that when I input any string, as long as I type out "word" first, I get proper output.
But is this program actually valid
It compiles and therefore is valid from a syntax perspective. It's also fine in order to check that a prefix is used.
However, there are at least two ways to get undefined behaviour:
scanf might store more than 1000 characters (read 999 and one for the final \0)
scanf might read none if the input does not start with "word"
You should therefore check the result of scanf, initialize word, and also limit the maximum number of characters that scanf reads:
#include<stdio.h>
int main()
{
char word[1000] = {0};
int ret = scanf("word%999s", word);
if ( ret == 1 ) {
printf("%s", word);
}
}
this program is valid ,but you have to be careful about buffer overflow , which means if user input more than 999 chars this will lead to undefined behavior , so I suggest this:
scanf("word%999s", word);
also as you said as long as I type out "word" first ,otherwise char word[1000] will be uninitialized.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
We got an assignment to make a program to read what is written inside our text file (name, student number, course, year, section, etc.. etc..) But I can't seem to make it work, can you tell me what's wrong?
#include <windows.h>
#include <conio.h>
#include <stdio.h>
struct record
{
char name[50],number[50],course[50],gender;
int year, section;
float midterm,final,average,sum;
};
int main()
{
int a=1,n;
int passed=0,failed=0;
FILE *fp;
fp = fopen("BSU.txt","r");
if(fp==NULL)
{
printf("ERROR!");
getch();
}
struct record student[25];
printf("Please input the number of students: ");
scanf("%d", &n);
for(a=0;a<n;a++)
{
fscanf(fp, "%f", student[a].average);// I CANNOT MAKE THE FSCANF WORK!!//
}
getch();
}
It should be
fscanf(fp, "%f", &student[a].average);
instead of
fscanf(fp, "%f", student[a].average);
But this allows you only to read a file containing numbers, for example:
1.5
1.9
2.7
The file you want to read is more compilcated.
So in your for loop you need to read 10 lines, extract the relevant information from each line, store that information in the corresponding field of your record, and store the record somewhere.
You need to consider the input file format.
When you're calling fscanf the 'cursor' is located at the first line of your file. What you need to to is to bring the cursor to the line you want to read.
Student Name: Andrea Zoelle Jacinto <-- cursor is located at the beginning of this line
Gender: M
Student Number: 2015-04711-MN-0
Course: BSIT
Year: 1
Section: 2
Midterm Grade: 2.00
Final Grade: 1.75
Average Grade: 1.8 <-- you need the cursor here
To achieve that you can use fgets in an while loop to get rid of the lines before the desired line.
char line[256];
while( fgets(line, 256, fp) && line[0] != 'A'); // line[0] != 'A' makes the loop stop when it reached the desired line
Now your cursor is at the desired line, however you need to get rid of the text in front of the value you want to read.
Average Grade: 1.8 <-- get rid of "Average Grade: "
The good thing is line already contains this line, so you can use sscanf to read formatted from this string.
sscanf(line, "%*s %*s %f", &student[0].average); // note the ampersand in front of student[0].average to get its address
Using %*s makes sscanf ignore the words "Average" and "Grades:" so %f will read the desired value.
Because it looks like your homework, I will not give you the solution but I tell you where is bug.
You are using fscanf in the incorrect way. This line:
fscanf(fp, "%f", &student[a].average);
is telling something like: "take somevalue (float type) and write it to student[a].average".
It can't work in your situation, because your data structure is more compilacted.
What have you to do?
First, try to write all data from the file on output.
After that, you should try to parse the line which are you interest :)
Read about getline, sscanf. It could be very helpful for you :)
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I am trying to get the integers values to be passed to a linked list from a text file.
The problem is that the text file is structured as columns and rows.
This is an example below regarding the text file:
5:0:3
4:1:2
3:1:1
4:2:2
3:3:1
How can I get these values? Noting that my program should notice the : and not only the EOF. I wrote a similar program but it can't take care of the colon. it only scans the integer values until the EOF.
You can use fgets() to read lines and then sscanf() to parse each line. If the lines, contain only 3 integers then it can be done as:
int i, j, k;
char str[256];
FILE *fp = fopen("filename", "r");
if(!fp) {
/* File opening error */
}
while(fgets(str, sizeof str, fp)) {
char *p = strchr(str, '\n');
if (p) *p = 0; // remove the trailing newline, if
if( sscanf(str, "%d:%d:%d", &i, &j, &k) == 3) {
printf("%d %d %d\n", i, j, k);
/* do processing with i, j & k */
}
else {
/* failure */
}
}
You can use fscanf as
fscanf(fp, "%d:%d:%d", &var1, &var2, &var3);
You can read in the entire line as a string using getline.
Then you can use the string function find() to find the :
After that you'll have saved in what position in the string the : was found, and you can convert the character that is one position behind the : into a integer using atoi(). That works for the first 2 numbers.
For the last number, you do the same thing but instead of : you look for a space.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
code isnt working on line 19 & 20
i'm trying to get a string named hotel...
when i put gets(hotel) almost over everything surprisingly code starts working...but not in the middle of the code.!!!!!
#include<stdio.h>
main()
{
char topping[24];
char hotel[50];
int slices;
int month,day,year,i;
float cost;
printf("how much a pizza cost in your area? ");
printf("enter in $XX.XX\n");
scanf("$%f",&cost);
printf("what is your favorite one word pizza topping?\n");
scanf("%s",&topping);
printf("how many slices of %s of pizza \n",topping);
scanf("%d",&slices);
printf("which is your favorite hotel in town?\n");
gets(hotel);
printf("what is today's date (enter in XX/XX/XXXX format)\n");
scanf("%d/%d/%d",&day,&month,&year);
printf("\n\n\n\n\nwhy not treat yourself %d slices of %s pizza in %s on %d/%d/%d it will cost you only %.2f",slices,topping,hotel,day,month,year,cost);
return 0;
}
This is the same thing I talked about recently here: D lang - Using read and readln() in the same program although in C instead of D so the solution is slightly different but same explanation.
The scanf stops on whitespace, which is a newline... which gets sees as the end of input and thus reads an empty line.
The solution is to consume that newline before continuing:
printf("how many slices of %s of pizza \n",topping);
scanf("%d",&slices);
fgetc(stdin); // ADDED THIS LINE TO READ PAST THE NEW LINE CHARACTER
printf("which is your favorite hotel in town?\n");
gets(hotel);
PS don't use gets, use fgets(hotel, 50, stdin); instead. The 50 there is the size of the buffer, ensuring it doesn't overflow.
There are a couple of things I would change.
When you are reading topping & hotel, they are strings, you do not need to pass that by reference. So pass scanf("%s", topping);
When you are doing the strings, you want to make sure you don't allow the user to overfill the array. See this for an example of how to limit the input size.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
Right so i have a program that will find a strings place in a file, and the line it belongs to. Now the Find works fine but the string compare has a big problem i cannot get my head around, here is the code:
#include <stdio.h>
#include <conio.h>
#include <string.h>
int main(void){
int loop, line;
char str[512];
char string[512];
FILE *fd = fopen("Student Passwords.txt", "r");
if (fd == NULL) {
printf("Failed to open file\n");
return -1;
}
printf("Enter the string: ");
scanf("%s",string);
printf("Enter the line number to read : ");
scanf("%d", &line);
for(loop = 0;loop<line;++loop){
fgets(str, sizeof(str), fd);
}
printf("\nLine %d: %s\n", line, str);
str[strlen(str)-1] = '\0';
if(strcmp(string,str) == 0 )
{
printf("Match");
}
else
{
printf("Nope");
}
fclose(fd);
getch();
return 0;
}
Someone told me to use strlen, which i of course inserted into the code but i think it just makes it worse, i am not sure what to do now can i have some help?
Text file:
Password
abcdefg
Star_wars
jedi
Weapon
Planet
long
nail
car
fast
cover
machine
My_little
Alone
Love
Ghast
Thanks
Edit: Input: Random word , Input: line number. Program will go to the line chosen and scan the string stored there, and compare it with the input string. Output: Either Match or Nope.
Edit: Input: Password, 1 Output: Match , Input: Password, 2 Output: Nope.
Your program works fine for me except that your text file have trailing spaces after some words. but your user input do not have spaces. Try to print the lengths of the user input and read line and you can find out.
Remove all trailing spaces from your text file and there should not be any problem.
Also as others have mentioned, it is good to use similar input functions in your code. you can use fgets for user input also.