lineBuffer in C++ - c++

I was just browsing some coding stuff and noticed this code:
int main(int argc,char** argv)
{
ifstream file;
string lineBuffer;
file.open(argv[1]) ;
while (!file.eof())
{
getline(file, lineBuffer);
if (lineBuffer.length() == 0)
continue; //ignore all empty lines
else
{
//do your code here
}
}
return 0;
}
I have searched for the concept of a lineBuffer all over the net but found no relevant answer.
Can anyone help me to understand how lineBuffer is used to read a file line by line?

string lineBuffer;
This is a variable called lineBuffer. It's not a concept to be understood and it doesn't read files, it's just a string with a name, it could just as easily have been called:
string fred;
but because it is used as a buffer to hold each line of text, it is more sensible and helpful to call it lineBuffer.
Wherever you found that code, stop reading it, the code is broken and written by someone who doesn't know C++ very well. This part is broken:
while (!file.eof())
{
getline(file, lineBuffer);
It should be done like this instead:
while (getline(file, lineBuffer))
{

The lineBuffer is a string where you are asking C++ to put the line it reads. Once the line is in that string, they check whether there was any content in that line, and if not, skip processing it.

Related

Why Does getline() Doesn't Read anything from a file?

I have made a code which accepts a txt file as input, and parse, and put them in 2d array myarray[][2].
Input file structure looks like this:
aaa/bbb
bbb/ccc
ccc/ddd
And it should be parsed like this:
myarray[0][0] = "aaa"
myarray[0][1] = "bbb"
myarray[1][0] = "bbb"
myarray[1][1] = "ccc"
The code which I made to do this:
void Parse_File(string file){
ifstream inFile;
inFile.open(file);
if (inFile.is_open()){
inFile.clear();
int lines = count(istreambuf_iterator<char>(inFile), istreambuf_iterator<char>(), '\n');
string myarray[lines][2];
int mycount = 0;
do{
getline(inFile, input);
myarray[mycount][0] = input.substr(0, input.find("/"));
myarray[mycount][1] = input.substr(input.find("/") +1, input.length());
mycount++;
}while (input != "");
}else{
Fatal_Err("File Doesn't Exist");
}
inFile.close();
}
But myarray doesn't have anything in it after this function. The do-while statement doesn't loop. I can't figure out why. Any help is appreciated. Thanks.
Your file had a few issues, but the major one was: You forgot to bring your file reading pointer back to the beginning of the text document. The count function took the said pointer to the end, so you needed to bring it back.
So you need to use the seekg() function to drag the pointer wherever you wish to.
See if the code below works for you
void Parse_File(string file)
{
ifstream inFile;
inFile.open(file);
if (inFile.is_open())
{
inFile.clear();
int lines = count(istreambuf_iterator<char>(inFile), istreambuf_iterator<char>(), '\n');
//Pitfall : By counting the lines, you have reached the end of the file.
inFile.seekg(0);// Pitfall solved: I have now taken the pointer back to the beginning of the file.
....
....//Rest of your code
}
}
Also, you need to learn debugging so that you understand your code more easily. I would recommend visual studio code for debugging c++.
Move "getline(inFile, input);" to the end of your loop and call it again right before you enter. input is probably "" before you enter the loop, so the loop is never called and input is never updated.

Whats the optimal conditional for counting number of lines in text file?

I've got the following code where I'm trying to count the number of lines in an input file, and I've tried several different ways of implementing it, but no luck.
int checkData(string File)
{
string temp;
int linecount = 0;
ifstream input(File);
input.open(File);
while ()
{
getline(input,temp);
linecount++;
temp.clear();
}
return linecount;
}
So far, I've tried:
while(!input.eof())
{
...
}
and
while(getline(input,temp).good())
{
...
}
The first doesnt break the loop, and I'm not quite sure why. (I'm fairly sure) that getline has a built in stream buffer, so it should automatically read the net line everytime I pull in a line and throw it back out, but no dice. For the second, the loop doesn't execute at all, which still doesn't make sense to me (that says that the first line of file isn't good input?).
The test file I'm using is:
this is a test this Cake
this is a test this Cake
this is a test this Cake
this is a test this Cake
So linecount should be returning as 4 when executing correctly. Before I execute this, I've already checked to make sure the file is opening correctly.
output
int number_of_lines = 0;
string line;
ifstream myfile("textexample.txt");
while (std::getline(myfile, line))
++number_of_lines;
Hope it helps.

How to read lines from a file using the ifstream?

I have a text file with the following information in it:
2B,410,AER,2965,KZN,2990,,0,CR2
2B,410,ASF,2966,KZN,2990,,0,CR2
2B,410,ASF,2966,MRV,2962,,0,CR2
2B,410,CEK,2968,KZN,2990,,0,CR2
2B,410,CEK,2968,OVB,4078,,0,CR2
2B,410,DME,4029,KZN,2990,,0,CR2
2B,410,DME,4029,NBC,6969,,0,CR2
2B,410,DME,4029,TGK,\N,,0,CR2
(it is airline route info)
I'm trying to loop through the file and extract each line into a char* - simple right?
Well, yes, it's simple but not when you've completely forgotten how to write successful i/o operations! :)
My code goes a little like:
char * FSXController::readLine(int offset, FileLookupFlag flag)
{
// Storage Buffer
char buffer[50];
std::streampos sPos(offset);
try
{
// Init stream
if (!m_ifs.is_open())
m_ifs.open(".\\Assets\\routes.txt", std::fstream::in);
}
catch (int errorCode)
{
showException(errorCode);
return nullptr;
}
// Set stream to read input line
m_ifs.getline(buffer, 50);
// Close stream if no multiple selection required
if (flag == FileLookupFlag::single)
m_ifs.close();
return buffer;
}
Where m_ifs is my ifStream object.
The problem is that when I breakpoint my code after the getline() operation, I notice that 'buffer' has not changed?
I know it is something simple, but please could someone shed some light onto this - I'm tearing my forgetful hair out! :)
P.S: I never finished writing the exception handling so it is pretty useless right now!
Thanks
Here is a fix with some important c++ libraries you may want to learn, and what I believe a better solution. Since you just need your final result to be strings:
// A program to read a file to a vector of strings
// - Each line is a string element of a vector container
#include <fstream>
#include <string>
#include <vector>
// ..
std::vector<std::string> ReadTheWholeFile()
{
std::vector<std::string> MyVector;
std::string JustPlaceHolderString;
std::ifstream InFile;
InFile.open("YourText.txt"); // or the full path of a text file
if (InFile.is_open())
while (std::getline(InFile, PlaceHolderStr));
MyVector.push_back(PlaceHolderStr);
InFile.close(); // we usually finish what we start - but not needed
return MyVector;
}
int main()
{
// result
std::vector<std::string> MyResult = ReadTheWholeFile();
return 0;
}
There are two basic problems with your code:
You are returning a local variable. The statement return buffer; results in a dangling pointer.
You are using a char buffer. C-style strings are discouraged in c++, you should always prefer std::string instead.
A far better approach is this:
string FSXController::readLine(int offset, FileLookupFlag flag) {
string line;
//your code here
getline(m_ifs, line) //or while(getline(my_ifs, line)){ //code here } to read multiple lines
//rest of your code
return line;
}
More information about std::string can be found here

Reading BSDF data format

I have been required to write a function that reads the BSDF data format defined by Zemax
An example of such file can be found at the following page: BSDF file example
I would like to use, if possible, only standard ifstream functions.
I have already prepared all the necessary datamembers inside a dedicated class.
I am now trying to write the function that reads the data from the file.
Problems:
how do I exclude comment lines? as documented, they start with an hash # I was going for something like
void ReadBSDFFile(myclass &object)
{
ifstream infile;
infile.open(object.BRDFfilename);
char c;
infile.get(c);
while (c == "#") // Problem, apparently I cannot compare in this way. How should I do it?
{
getline(infile, line);
infile.get(c);
}
// at this point I would like to go back one character (because I do not want to lose the non-hash character that ended up in *c*)
infile.seekg(-1, ios_base::cur);
// Do all the rest
infile.close();
}
in a similar way, I would like to verify that I am at the correct line later on (e.g. the "AngleOfIncidence" line). Could I do it in this way?
string AngleInc;
infile >> AngleInc;
if (AngleInc != "AngleOfIncidence")
{
//error
}
Thanks to anyone who will comment/help. Constructive criticism is welcomed.
Federico
EDIT:
Thanks to Joachim Pileborg below, I managed to proceed up to the data blocks part of the file.
Now I have the following problem. When reaching the datablocks, I wrote the following piece of code, but at the second iteration (i = 1) i receive the error message for the TIS line.
Could someone help me understand why this does not work?
Thanks
Note: blocks is the number on the AngleOfIncidence line, rows the one on the ScatterAzimuth line and columns the one on the ScatterRadial. I tested and verified that this part of the function works as desired.
// now reading the data blocks.
for (int i=0; i<blocks; i++)
{
// TIS line
getline(infile, line);
if (line.find("TIS") == string::npos)
{
// if not, error message
}
// Data block
for (int j=0; j<rows; j++)
{
for (int k=0; k<columns; k++)
{
infile >> object.BRDFData[i][j][k];
}
}
}
EDIT 2:
solved adding infile.seekg(+2, ios_base::cur); as a last line of the i loop.
The reading loop could be simplified like this:
std::string line;
while (getline(infile, line))
{
if (line[0] != '#')
{
// Not a comment, do something with the line
if (line.find("AngleOfIncidence") != std::string::npos)
{
// On the AngleOfIncidence line, do special things here
}
}
}
It's might not be optimal, just something written at the top of my head, but should work.
From the description of the format you provided:
Any line that starts with the # symbol is ignored as a comment line.
So what you need to do is the following
Read the file line by line
If the line starts with # ignore it
Otherwise process the line.
The while you have used is wrong. Use the getLine function instead and compare its first character with the #.

Getting input from a file in C++

I am currently developing an application, which gets the input from a text file and proceeds accordingly. The concept is the input file will have details in this fomat
A AND B
B OR C
Each and every line will be seperated by a blank space and the input must be taken from the text file and processed by logic. I use a TCPP compiler and i am facing problems reading the input. Please help me with the issue...
Reading input a line at a time is normally done with std::getline, something like this:
std::string line;
std::ifstream infile("filename");
while (std::getline(line, infile))
// show what we read
std::cout << line << "\n";
If you're having trouble with things like this, you might consider looking for a (better) book on C++ than whatever you're now (hopefully) using.
Following can be used straightaway:
BOOL ReadFile(CString filename)
{
BOOL bRead = TRUE;
std::ifstream m_strmFile;
m_strmFile.open(filename, std::ios::in);
char pszLine[256];
memset(pszLine, 256, 0);
if (m_strmFile)
{
// Read whatever number of lines in your file
for (unsigned int i = 0; i < 5/*number of lines*/; i++)
m_strmFile.getline(pszLine, 256);
// Do whatever you want to do with your read lines here...
}
else bRead = FALSE;
return bRead;
}
are you using headr files like:
include
or #include and you can make use of the fileobject.getline(), (do check its proper syntax.) function in C++ or for char by char use fileobject.get(ch) kind of function