-
lines of a text file
hi, say I had a text file that was read by my program, how would I be able to get it read each line seperately, storing each line in a seperate variable and if the line had nothing in it, the program would ignore that line. Is this possible?
Thanks
-Chris
-
Offhand, try first counting the lines (count "\n"s). Then use that count with new to create an array with size of number of lines. Read the lines into the array. Check for empty lines before reading the lines into the array, and skip those lines.
Haven't tried it, but that's an outline, anyway
-
anybody got some code to demonstratre this becuase i am confused about what your talking about
-
-
i've looked at this already but i don't understand it and when i compile it it doesn't work
-
You would have to use something like fgetc. Check for leading whitespace, nelwines, and end of file characters. This is getting on the edge of having to fully understand the implimentation of a string class.
-
could you please explain this to me?
-
Code:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
int main()
{
ifstream file("myfile.txt"); // or whatever
vector<string> Lines;
string CurrentLine;
while(!file.eof())
{
getline(file, CurrentLine);
if(!CurrentLine.empty()) // store it if not empty
Lines.push_back(CurrentLine);
}
// show the stored lines
for(int i = 0; i < Lines.size(); i++)
cout << Lines[i] << endl;
file.close();
return 0;
}
-
or try this...
Code:
#include<iostream.h>
#include<string.h>
#include<fstream.h>
int main()
{
ifstream infile;
char str[255] = "",
str2[255] = "";
cout<<"enter filename\n";
cin>>str;
cout<<"\n";
infile.open(str, ios::nocreate);
if(infile.fail())
{
cout<<str<<" not found.";
return 0;
}
do
{
infile.getline(str2, 255, '\n');
if(strlen(str2) > 0)
{
cout<<str2<<"\n";
}
}
while(!infile.eof());
infile.close();
return 0;
}