I can't load text from file properly - c++

I can't seem to find what's wrong with this piece of code. It's a function that will load a couple of simple settings from a file. The problem is that the cout in the while loop doesn't show anything, only blank and an end line. It was put there for testing. Also the array "config_temp" only has blanks. I always used this method and even looked in previous projects and tutorials how it was written there. I can't find the expenation for this. Please help.
void load()
{
string config_temp[5];//temporary array into which the config is loaded to
int cc=1;//config counter
int ac=0;//array counter
ifstream file;
string line;
file.open("config.txt",ios::in);
while(getline(file,line))
{
if(cc%2!=1)
{
cout<<line<<endl;
config_temp[ac]=line;
ac++;
}
cc++;
}
file.close();
for(int i=0;i<=4;i++)
{
cout<<config_temp[i]<<endl;
}
frames=sti(config_temp[0]);
res_width=sti(config_temp[1]);
res_height=sti(config_temp[2]);
states=sti(config_temp[3]);
frequency=sti(config_temp[4]);
global_state=0;
}

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.

C Builder (C++) AnsiString Length method

I am used to program in c#, but now i had to help my roommate with a c++ project.
This is the "not working code" :
void HighlightKeyWords::Highlight(TRichEdit eMemo,TRichEdit RichEdit1)
{
ifstream file("KeyWords.txt");
AnsiString temp;
int maxWordLength=0;
if(file.is_open())
{
while(file>>temp)
{ if(temp.Length()> maxWordLength)
{
maxWordLength=temp.Trim().Length();
}
keyWords.push_back(temp);
}
file.close();
}
else
{
ShowMessage("Unable to open file. ");
}
for(unsigned i=0;i<KeyWords.size();i++)
{
richEdit1->Text=KeyWords[i];
}
eMemo->Text=MaxWordLength;
}
I get a list of keywords from the file. In MaxWordLength i want to know to maximum length of a word ( words are separated by new line in the text file ). When I do the temp.Length, i get 695 ( the number of all characters in the file ). Why am I not getting the actual length of the word i am adding to the vector?
Thank you!
LE: I also did the MaxWordLength logic in the for below, the for where i put the items in the RichEdit.
Use file.getline() instead of the >> operator, which won't produce the desired output in your case, but gives you the full file content as result. So AnsiString().Length() is not your problem. Just modify part of your code to get it working as intended:
char buffer[255];
if(file.is_open()){
while(file.getline(buffer, sizeof(buffer))){
temp = AnsiString(buffer).Trim();
if(temp.Length()> maxWordLength) maxWordLength=temp.Length();
keyWords.push_back(temp);
}
file.close();
}

Issue reading multiple lines from .txt file in C++

I'm trying to create a student database system for a school project. I'm trying to create a function that will search a .txt file for the student id and return all of the other variables on the string. This is working great if I search for the id of the student on the first line of the txt file but isn't capturing anything if I search for a student on another line. Am I missing something obvious?
The student data is 16 strings delimited by commas on each line. The student ID is the first string.
Thanks for any assistance!
StudentType findStudent(int studentToFind)
{
ifstream inFile;
inFile.open("students.txt");
string currentLine;
string dataRead[16];
istringstream is;
int currentStudent;
if (inFile)
{
while (getline(inFile, currentLine))
{
is.str(currentLine);
for (int i = 0; i < 16; i++)
{
getline(is, dataRead[i], ',');
}
currentStudent = stoi(dataRead[0]);
if (currentStudent == studentToFind)
{
/*
Do stuff here
*/
inFile.close();
return foundStudent;
}
cin.ignore(); // Not sure if this is needed but I was trying to
// clear the \n char if that was causing the issue
}
}
}
First : you aren't using cin, so get rid of cin.ignore().
Second : you should make sure you ALWAYS close infile at the end... so I would suggest not returning early or closing early, but using a break statement to exit your loop and then have a single return of whether you found it or not.
Third: Now that you removed all the 'gorp' we can finally hone in on the problem ... effectively the question is do we read all the lines?
Well let's check that, try printing out currentLine each time at the beginning of the while loop, if you know currentLine is updated properly, is is getting updated each time? yes...
ok then look at your next loop let's print out currentStudent each time... does currentStudent print the right value for each line? i.e. is the getline write into dataRead[i] actually writing what you think it should be to the right space?
Did you find the problem yet?
This is the kind of problem you need to learn how to solve yourself using print statements and a debugger. That what its for. If you are in visual studio run in debug mode and step through it... if not, use gdb. learn it and get used to it, you'll be using it a lot!
good luck

lineBuffer in 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.