-
Getline Problem
Hi! I changed the line to new_name.getline ! But now it only gets the last lines of
the datafile. Why is that?
#include <fstream.h> // Header file used to open/close files
#include <stdlib.h> // Header file that includes the 'exit' function
#include <cstring.h> // Header file that is used to declare variables as strings
#include <io.h> // Header file that includes the 'EOF' function
char name [256];
char lname [256];
char *namearray [50]; // Declares an array
char *lnamearray [50];
char infob [200];
int a =-1;
void main ()
{
ifstream new_name; // Declares the input stream
new_name.open ("c:/names.txt", ios::in); // Opens the textfile
if (!new_name) // Checks to see if file is in the disk
{
cout << "Error opening file.\n"; // Displays information on to the screen
exit(1); // Exits the program
}
while (new_name)
{
a++; // Counter
new_name.getline (name, 255, '\n');
new_name.ignore();
namearray [a] = name; // Stores it into an array
eof(0); // Ends the loop when it is at end of file
}
for (int v=0; v < a; v++)
cout << namearray [v] << " " << endl;
// Displays values from the file
new_name.close(); // Closes the file
}
-
oh man!
>namearray [a] = name;<
what's that???
you have to use strcpy if you are working with char*
but why do you use char* ?? i mean vector<string> would be so easy to deal with as an array...
and string is much easier than char*
and >eof(0);<
haven't seen it yet... but i don't work that much with c++, so what does it do?
-
Try this out, then compare the two programs and see what changes I made. And just so that I don't get complaints, void main is not standard and therefore you shouldn't do it. The standard dictates that int main(void) should be used.
Code:
#include <fstream>
#include <stdlib.h>
#include <cstring>
#include <iostream>
using namespace std;
void main()
{
char name[256];
char *namearray[50];
int a = -1;
ifstream new_name("names.txt");
if (!new_name){
cout << "Error opening file.\n";
exit(1);
}
while (!new_name.eof()){
a++;
new_name.getline (name, 255, '\n');
namearray[a] = new char[255];
strcpy(namearray[a], name);
}
for (int v=0; v < a; v++)
cout << namearray [v] << " " << endl;
new_name.close();
}
p.s. I had to create my own data file to test this, but it works quite well.
-Prelude
-
thank YOU very much!! it worked!!!~
~secyw~