I have to look through a file and take out the information of a student. It all works fine so far, there are 21 lines in the file, the first 20 contain information of a student and the final line contains just a single name. For some reason my while loop continues, sees that there's no information after that last line and stops but it still prints out that last line of the file with other lines of information in the in the output as well.
count = 0;
while(fscanf(fp, "%d", &average)!= EOF )
{
if(fscanf(fp, "%d", &average)!= EOF ){
printf("\n/////////////////////////////////////////////////////////////////////////////");
fscanf(fp, "%s", name);
fscanf(fp, "%s", initial);
fscanf(fp, "%s", surname);
printf("\n\n\tName: %s \tInitial: %s \tSurname: %s\n", name, initial, surname);
fscanf(fp, "%d", &year);
fscanf(fp, "%s", coursename);
fscanf(fp, "%s", group);
fscanf(fp, "%d", &average);
printf("\n\tYear: %d \tCourse Name: %s \tGroup: %s \tAverage: %d\n", year, coursename, group, average );
printf("\n\tThis is entry number %d\n", count+1);
printf("\n/////////////////////////////////////////////////////////////////////////////");
count++;
}
if(fscanf(fp, "%d", &average) == EOF ){
printf("\n\nThank you for using the program\n\nAll of the student records are now displayed\n");
}
}
fclose(fp);
return 0;
}
If the second last line for instance was
Mike (M) Johnson 3 IT A 66
it would print that out perfectly fine but the final thing in the file the name "John" it would print out
John Johnson 3 IT A 66
I don't understand firstly why it wouldn't take Mike Johnson's initial and secondly when it shouldn't print that line to begin with? I've tried setting the if statements and while statement to take the name as the end of the file but I think when I use "%s" to find that at the begining it seems to skip everything to the next string in the file over by 1, so Mike's name would become (M), and so on.
Related
I have written this program and I want every time I enter the while loop to read the next line from my text file and not the before lines. So far, this code with fscanf inserts in a list all the elements before the one I want. My text files have 4 elements per line and I do not want to read it all as a string also. For example, if the elements from line 1 have entered in the list, the next time in the loop I want to start from line 2 and not to read again the line 1 etc.
for(Time=0.0;Time<200;Time=Time+12.0) {
for(i=5;i<8;i++){
char to_open[32];
snprintf(to_open,32, "fptg_%d.txt", i);
printf("i=%d\n", i);
if ((fr = fopen(to_open, "r")) == NULL)
{
break;
}else{
fscanf(fr, "%d %d %d %lf",&rollnumber, &src, &dest, &gentime);
while(gentime<Time){
if (insertedpackets[i]<10){
printf ("-------------TIMESLOT-------------\n");
printf("time: %.1f\n",Time);
fscanf(fr, "%d %d %d %lf\n",&rollnumber, &src, &dest, &gentime);
insert(rollnumber,src,dest,gentime);
insertedpackets[i]++;
printf("insertedpackets[%d]:%d\n\n", i, insertedpackets[i]);
printf ("----------list till now-----------\n");
display();
printf ("----------------------------------\n\n\n\n");
}
else if (insertedpackets[i]>=10)
{
break;
}
}
I have this code:
char temp;
scanf("%c",&temp);
fgets(variable1,50,stdin);
strtok(variable1, "\n");
printf("%s ", variable1);
This gets a string with the possibility of having spaces and assigns it to the variable variable1. Later, I can print the string with no problem.
The problem comes when I add to code other fgetsfor gets other string in other variable.
if (1) {
scanf("%c",&temp);
fgets(variable2,50,stdin);
strtok(variable2, "\n");
printf("%s ", variable2);
}
The result complete is:
char temp;
scanf("%c",&temp);
fgets(variable1,50,stdin);
strtok(variable1, "\n");
printf("%s ", variable1);
if (1) {
scanf("%c",&temp);
fgets(variable2,50,stdin);
strtok(variable2, "\n");
printf("%s ", variable2);
}
variable1 always works correctly. But I try print in some phrases with %s variable2 but the result does not get the first character, only in second scanf. If I put HELLO, variable2 is ELLO.
I have tested using another temp variable, another data, etc. But always get the same error.
Why is this happening?
UPDATE
For more information. I use scanf because, if I do not use it, the program does not pause while waiting for the string. I use strtok(variable1, "\n"); to remove the line break.
This program is inside a while and in switch case. I put the complete code:
case 4: printf( "Put equipo: ");
scanf("%c",&temp);
fgets(equipo,50,stdin);
strtok(equipo, "\n");
if (Exists(equipo)) {
printf("Put Piloto ");
scanf("%c",&temp);
fgets(piloto,50,stdin);
strtok(piloto, "\n");
printf("You said %s and %s", equipo, piloto);
}
break;
If I introduce like Equipo HELLO and like Piloto FRIEND, the output is:
You said HELLO and RIEND
Re-written based on OP latest edits to post, and comments...
You describe the need to simply obtain two strings from user input, remove the newlines from each, then package both into a message to stdout. If this description actually matches what you need, change this code section:
...
scanf("%c",&temp);
fgets(equipo,50,stdin);
strtok(equipo, "\n");
if (Exists(equipo)) {
printf("Put Piloto ");
scanf("%c",&temp);
fgets(piloto,50,stdin);
strtok(piloto, "\n");
printf("You said %s and %s", equipo, piloto);
...
To this:
...
printf("enter equipo: ");
if(fgets(equipo, sizeof(equipo), stdin))
{
equipo[strcspn(equipo, "\n")] = 0; //remove newline
printf("enter piloto: ");
if(fgets(piloto, sizeof(piloto), stdin))
{
piloto[strcspn(piloto, "\n")] = 0;
printf("You said %s and %s", equipo, piloto);
}
}
...
Note: strtok(piloto, "\n"); works, but has problems if user just hits <return>
By the way, here are some other interesting ways to clear the newline
I do not understand your example code. Could you update the question with your actual code?
I assume scanf should not be there?
This code works fine for me:
char var1[50], var2[50];
fgets(var1, 50, stdin);
strtok(var1, "\n");
printf("Var1: %s\n", var1);
if (1) {
fgets(var2, 50, stdin);
strtok(var2, "\n");
printf("Var2 %s\n", var2);
}
Output:
Test1
Var1: Test1
Test2
Var2 Test2
This is a part of my 'Phonebook' program.
void viewall(){
int n, checking = 0;
char name[50];
fp = fopen("Phonebook.txt","r");
printf ("\n\n");
fscanf (fp, "%s %d", name, &n);
while (!feof(fp)){
printf (" %s +880%d\n", name, n);
fscanf (fp, "%s %d", name, &n);
++checking;
}
if (checking == 0){
printf (" Contact List is Empty. No Contacts to Show...");
}
printf ("\n\n");
fclose(fp);
menu();
}
This part displays all the contacts in list. But if any contact name has two parts they get separated. For example: I enter Anik Shahriar as name and then enter my number. I looked at my file and this data was there how it should be.
Anik Shahriar 01*******93
But when I wanted to display all the contacts. It got printed like this:
Anik 0
Shahriar 01*******93
How can i make the program print the whole line ?
This behaviour is caused by the lines
fscanf (fp, "%s %d", name, &n);
The format identifier %s scans for a single string. Any whitespace character ends the scan.
http://www.cplusplus.com/reference/cstdio/scanf/
%s
String of characters
Any number of non-whitespace characters,
stopping at the first whitespace character found. A terminating null
character is automatically added at the end of the stored sequence.
I suggest to use ca CSV file and use a format string like.
scanf("%[^,] %d", name, number)
Dont forget to test the scanf result value.
My code keeps closing before reading the file, I made a comment where it closes. Does anyone know why it wont work? I showed it to my lecturer but she couldn't figure it out and then she had to leave so I was wondering if anyone here could figure it out!
#include <stdio.h>
#include <stdlib.h>
#define RESULT_MAX = 100;
#define RESULT_MIN = 0;
int main()
{
int studentId;
char firstName[20];
char lastName[20];
int result;
FILE *fPtr;
if ((fPtr = fopen("student.txt", "w")) == NULL)
{
printf("File could not be opened\n");
//exit(0);
}
else
{
printf("Enter the Id, first name, last name and result\n");
scanf("%d %s %s %d", &studentId, firstName, lastName, &result);
while(!feof(stdin) )
{
fprintf(fPtr, "%d %s %s %d\n", studentId, firstName, lastName, result);
scanf("%d %s %s %d", &studentId, firstName, lastName, &result);
}
fclose(fPtr);
}//else end
// MY PROGRAM ENDS HERE AND WONT CONTINUE!
if ((fPtr = fopen("student.txt", "r")) == NULL)
{
printf("File could not be opened\n");
//exit(0);
}
else
{
printf("Id, first name, last name, result ");
fscanf(fPtr, "%d %s %s %d", &studentId, firstName, lastName, &result);
while(!feof(fPtr) )
{
printf("%d %s %s %d \n", studentId, firstName, lastName, result);
fscanf(fPtr, "%d %s %s %d", &studentId, firstName, lastName, &result);
}//end while
fclose( fPtr );
}//end if
}
the problem is actually the line: 'while(!feof(stdin) )'
because feof() only becomes valid when the program
tries to read past the end of the 'stdin' file.
This is something that cannot be accomplished
suggest
modifying the program to:
1) read into a local buffer[] array, in a loop,
2) using fgets() as the loop control
3) have a leading 'q' (or similar) as an indication of having read all input
4) output a prompt for every input line
5) if going to parse the fields, parse them using
strtok()/atoi() strncpy() strncpy() atoi()
or perhaps
sscanf()
6) check first char of input buffer[] for the end marker (the 'q' above)
to exit the input loop before parsing
there is a similar problem with the
loop reading the file
I.E. do not use feof() for loop control
rather use fgets()
to differentiate each line of input written to the file, modify
the fprintf(fPtr, ... ) format string to include a trailing '\n'
Currently I'm doing my C programming homework. I'm facing a problem that I need to add some records to a text file using fprintf, then display out all the records within the file using fscanf. But here the display problem. It only skip the first character in the text, and display the rest.
Example in the textfile,
hello haha 400 500 60
hello2 haha2 500 600 70
We need to fscanf this file into display in command prompt. But in result show me...
ello haha 400 500 60
hello2 haha2 500 600 70
The rest of characters is okay, but for the first character, it skipped.
So this is my codes.
Fscanf's part
if ((ch = fgetc(fp)) != EOF){
while(fscanf(fp,"%s %s %d %d %d",code,name,&cost,&price,&stock) == 5)
{
printf("%-20s %-20s %-20d %-20d %-20d\n",code,name,cost,price,stock);
}
}else{
printf("Record not found in the stock database.\n");
puts("");
}
Fprintf's part
fprintf(fp,"%s %s %d %d %d\n",code,name,cost,price,stock);
So, how to read the first character ?
Your fgetc(fp) read the first h of the first hello, so now the file pointer is at e of hello. Further calls of your fscanf will read from e onwards. A simple soultion would be to add a printf("%c", ch) just above your while loop in your if condition. I.e,
if ((ch = fgetc(fp)) != EOF){
printf("%c", ch);
while(fscanf(fp,"%s %s %d %d %d",code,name,&cost,&price,&stock) == 5)
{
printf("%-20s %-20s %-20d %-20d %-20d\n",code,name,cost,price,stock);
}
}else{
printf("Record not found in the stock database.\n");
puts("");
}
The problem that you are having is that fgetc() is pulling your first character, as mentioned in the comment. In order to get the first character, you either need to store this character somewhere and append it to your output at the beginning, or else use a different method to check that the first character is not EOF.
Note that you could also cause definite problems if your first item was only one character long--Then your fscanf() would no longer have a 1st string to look at.
if ((ch = fgetc(fp)) != EOF){
ungetc(ch, fp);
while(fscanf(fp,"%s %s %d %d %d",code,name,&cost,&price,&stock) == 5)