-
Reading from file
Can someone pleaseeee tel me how do I read names(5) from a file and store it into an array...
I've tried everything I know but I just can't do it...
It's only a couple line of codes but I can't seem to do it.
Can someone show me some codes as how it can be done.
I'm only a newbie so if u can try to keep it simple :)
Pleaseeeeeee help... I'vre been trying for awhile now and I'm still where I started from.
Once again pleaseeeeeeee help... It's greatly appreciated!!!!
-
Post what you've done so far. Also, give us an idea of the layout of the file you are trying to read.
-
It depends on how you wrote your names to your output file.
If you did it the easy way, you would do the following:
Code:
//...
int x = 0; //Used to navigate through the array.
int n = 10; //Or how many layers in your array.
char myArray[10]; //A sample array.
ifstream.infile;
infile.open("data.dat"); //Or what you called your data file.
for(x = 0; x < n; x++) {
infile.get(myArray[x]); //Input to the array on the (x)th layer.
infile.ignore(80,'\n');
}
//...
I believe this code will work as is, if not, error check it. At least you will get the basics of how to do it. If not, ask for more help.
-
Try this...
First, make a file in notepad called "textfile.txt" like this:
Paul
Bob
Joe
Mark
Larry
Then save it in the same directory as the following c program. Everything should work fine (except you should fix the formatting as I can't get the program to display with all the proper indentations into this message).
#include <iostream> /* Needed for output to screen and input from keyboard */
#include <fstream> /* Needed for input/output to/from files */
using namespace std; /* Tells the compiler that the program will be using names that have a defined meaning in the std namespace */
int main()
{
ifstream in_stream; /* Creates a 'stream' or a connection called "in_stream" that will take info in from a file */
char name[10]; /* Sets aside memory to accept a string 10 characters long */
int x=0; /* Makes variable used for counting the number of names */
in_stream.open("textfile.txt"); /* Creates a link to the file */
while (!in_stream.eof()) /* Keep repeating the following commands as long as you haven't reached the end of the file (eof) */
{
in_stream >> name; /* Take the first character in the file, and put it into the x-th element in the string called "names" */
x = x + 1; /* Increases the number of names it has found by one */
cout << "Name #" << x << " was " << name << "\n"; /* Spits out a name that you read in */
}
in_stream.close(); /* Closes the link to the file */
cout << "The file contained " << x << " names.\n"; /* Outputs how many names were in the file */
return 0; /* Return a value of zero to signal the program ran succesfully */
}
-
>>>x = x + 1; /* Increases the number of names it has found by one */
x++; or x += 1; would do the same thing and is easier to read/code :D