Hi, I'm trying to read some lines of text from a file. This is the code that I've got so far, it seems to be working apart from the fact it only reads the first line of text and prints it to the screen.
//A program that calculates the reduced mass of diatomic molecules.
//The following libraries will be used.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
usingnamespace std;
int main()
{
int selection;//Defines the selection variable to determine the input.
printf("A program that works out the reduced mass of diatomic molecules.\n\n");//Prints the introductory message.
printf("Would you like to input the data from the keyboard or a .txt file?\n");//Allows the user to choose the input.
printf("1. From a .txt file ");
printf("2. From the keyboard\n");
printf(":");
scanf("%d",&selection);//Assigns the value of the selection int variable.
FILE *FP;
char a[100];
printf("Please input a filename including the .txt extension:"); scanf("%s",a);
FP = fopen(a,"r");
if (FP==NULL)
{
printf("Error Reading File");
}
elseif (FP!=NULL)
{
fgets (a,100,FP)!=NULL;
printf("%s",a);
fclose(FP);
}
return 0;
}
I've had a look in the tutorial, but the tutorial seems to be using a different library to the one we've been told to use in my course. For that reason I don't really want to change to a different library. I don't really understand the code that I've used either, it's pretty much been copied and the places I need to change it been changed. Does anyone know of any tutorials that cover reading from a file in relation to the libraries that I'ved used.
Not exactly a tutorial, but the reference section lists the various functions for file access, and each one is explained with a short code sample. If you are just beginning, it may be hard to decide which functions you need to use, and which are less common. But still, it could be worth a look here: http://www.cplusplus.com/reference/cstdio/