Changing from "getline" to "get" in c++ results in error - c++

I am reading from a file into a 2-D array in c++. I used a do while loop together with the eof(). The problem I was facing was, the program continues to read empty spaces when the characters in the file are exhausted. I realized that it was because of the getline function, so I used the get function instead. The program compiles and runs successfully but upon reaching the point where the characters in the file is to be read,(i.e in my console), the programs stops suddenly and returns with this error code -1073741795 (0xc00000ID). I would like to know why though, my major concern is how I will be able to read from the file and after the characters in the file is exhausted, the program stops reading from the file (so that no empty spaces are read).
Here is the sample code:
int k=0;
do{
name_input.getline(sample[k],num_char);
k++;
} while (!name_input.eof());
num=k-1;
PS: The input file is in the form;
Mr. Clark Smith
John B. Doe
Joshua Clement Johnson
each on one line
in a .txt file (notepad), after the 3rd name is empty space which my program still reads.

Using eof() is almost always wrong (see link in comments above). This is how to write the loop
int k = 0;
while (name_input.getline(sample[k],num_char)) {
k++;
}

Related

C++ reading text file line by line stops partway through

I have a file with 16,900,000 lines, each line contains 10 numbers (mix of int and floats). I'm trying to read this file line by line, modify each line slightly, and write to a series of new files. The code below works on a laptop running Windows Visa, but when I run it on a desktop running Windows 7, the output file does not contain all the data from the input file. The number of lines in the output file varies from 2500 to 40,000.
I've commented out all of the processing, and writing to files, and just write every 100th line to cout, the last line to print isn't the last line of the file.
// skipping code prior to the loop
// only including minimal code that reproduces the problem
ifstream infile((srcdir+filename).c_str());
string line;
int lcount=0;
while(getline(infile,line)){
if(line.find("#")==string::npos){
lcount++;
if(lcount%100==0){
printf("Generating tiles for %s: %d lines processed\n",filename.c_str(),lcount);
}
}
}
Questions:
Is there a maximum buffer size that I might be overflowing?
Can anyone see a problem with my code?
Is there any reason this would work fine on Windows Vista, but not on Windows 7?
In your question there is very little information. But I will put here my guesses:
I don't think lcount is in being incremented at the correct place in code. It get incremented only if '#' is not in the line (I'm guessing this is some sort of comment). But a line starting (o containing) '#' has to be counted too. So your code should be:
while(getline(infile,line)){
lcount++; // Increment every time.
if(line.find("#")==string::npos){
if(lcount%100==0){
printf("Generating tiles for %s: %d lines processed\n",filename.c_str(),lcount);
}
}
}
On the other hand, you should activate isftream exceptions in order to see whats going on, see here how to doit.
While trying to create a minimal full program that would reproduce the problem, I found the culprit.
I'm trying to secure the executable with the keylock dongle that my company is using. When I removed the check for the dongle, the entire file was read.

While loop construct in combination with getline function that continues until EOF

I am in a bind right now and the most frustrating thing about this is that I know what the problem is but, I cannot fix it :(...
My goal is to ultimately use getline to read lines of strings from redirected input (from a text file) and keep going until EOF is reached.
Example text file (contents):
Hello World!
Good Bye.
My source code(only includes the section where it will not work):
while (!(getline(std::cin, s_array)).eof()){ // it won't read second line
//do some awesome stuff to the first line read!
}
As far as I know, getline reads everything upto the newline and stops so how do we get it to keep reading because it always stops at Hello World!.
Use while (getline(std::cin, s_array)) { } instead.
std::getline() returns istream&, and istream::operator void*() makes it evaluated as false whenever any error flag is set.
You should definitely read Joseph Mansfield's blog post titled "Don't condition input on eof()" which describes this pitfall in details and provides a well justified guideline.

Character '<' in command prompt

I have a program I am writing, I have already completed it, but the requirement/specification for it says that:
In the "Command Prompt", if someone runs your program like this:
Peter David < savednames.txt
it should print out the names inside savednames.txt that matches each of "Peter" and "David"
I have written the program but my own is interactive, i.e it asks for the file, then the name you want to search for, and then it prints the matches.
It works perfectly fine, but I don't understand what the running of the program in command prompt like this: "Peter David < savednames.txt" means. I am using C++ on Microsoft Windows.
Please I need your help to explain it and how to implement it in my code...is it some kind of operator overloading or ...I don't understand!
On the command line, < is used for input redirection. The shell opens the file whose name follows the < and copies its contents into standard input for the program.
So if you called program input.txt, you could open the file and read its contents using std::ifstream or whatever; if you called program < input.txt, you could just read the file's contents from stdin using cin.
You can also do the same for output. Instead of opening a file and writing to it in your code, write to stdout and call your program as program > output.txt.
yourprogramname Peter David < savednames.txt
means that your program will be called with Peter as first argument, David as second argument, and its standard input will be connected to a stream reading out of savednames.txt.
You just need to read standard input one row at a time, and process it according to the arguments you received.
You just need to modify the code you already have to take the names from the command line (is there a limit? Could there be three names? Or four? You need to consider that) and to read the data from standard input stream, without any need of opening a file.

MFC C++ Always returning EOF when I have access to file

I am currently stuck in this problem that I do not have any idea to fix. It is regarding a previous question that I have asked here before. But I will reiterate again as I found out the problem but have no idea to fix it.
My program accesses a text file that is updated constantly every millisecond 24/7. It grabs the data line by line and does comparison on each of the line. If any thing is "amiss"(defined by me), then I log that data into a .csv file. This program can be run at timed intervals(user defined).
My problem is that this program works perfectly fine on my computer but yet it doesnt on my clients computer. I have debug the program and these are my findings. Below is my code that I have reduced as much possible to ease the explanation process
int result;
char ReadLogLine[100000] = "";
FILE *readLOG_fp;
CString LogPathName;
LogPathName = Source_Folder + "\\serco.log"; //Source_Folder is found in a .ini file. Value is C:\\phython25\\xyratex\\serco_logs
readLOG_fp = fopen(LogPathName, "r+t");
while ((result = fscanf(readLOG_fp, "%[^\n]\n", ReadLogLine)) != EOF) // Loops through the file till it reaches the end of file
{
Sort_Array(); // Here is a function to sort the different lines that I grabbed from the text file
Comp_State(); // I compare the lines here and store them into an array to be printed out
}
fclose(readLOG_fp);
GenerateCSV(); // This is my function to generate the csv and print everything out
In Sort_Array(), I sort the lines that I grab from the text file as they could be of different nature. For example,
CStringArray LineType_A, LineType_B, LineTypeC, LineTypeD;
if (ReadLogLine == "Example line a")
{
LineType_A.add(ReadLogLine);
}
else if (ReadLogLine == "Example line b")
{
LineType_B.add(ReadLogLine);
}
and so on.
In CompState(), I compare the different values within each LineType array to see if there are any difference. If it is different, then I store them into a seperate array to print. A simple example would be.
CStringArray PrintCSV_Array;
for (int i = 0; i <= LineType_A.GetUpperBound(); i++)
{
if (LineType_A.GetAt(0) == LineType_A.GetAt(1))
{
LineType_A.RemoveAt(0);
}
else
{
LineType_A.RemoveAt(0);
PrintCSV_Array.Add(LineType_A.GetAt(0);
}
}
This way I dont have an infinite amount of data in the array.
Now to the GenerateCSV function, it is just a normal function where I create a .csv file and print whatever I have in the PrintCSV_Array.
Now to the problem. In my client's computer, it seems to not print anything out to the CSV. I debugged the program and found out that it keeps failing here.
while ((result = fscanf(readLOG_fp, "%[^\n]\n", ReadLogLine)) != EOF) // Loops through the file till it reaches the end of file
{
Sort_Array(); // Here is a function to sort the different lines that I grabbed from the text file
Comp_State(); // I compare the lines here and store them into an array to be printed out
}
fclose(readLOG_fp);
It goes into the while loop fine as I did some error checking there in the actual program. The moment it goes into the while loop it breaks out of it suggesting to me it reach EOF for some reason. When that happens, the program has no chance to go into both the Sort_Array and Comp_State functions thus giving me a blank PrintCSV_Array and nothing to print out.
Things that I have checked is that
I definitely have access to the text file.
My thoughts were because the text file is updated every
millisecond, it may have been opened by the other program to write
into it and thus not giving me access OR the text file is always in
an fopen state therefore not saving any data in for me to read. I
tested this out and the program has value added in as I see the KB's
adding up in front of my eyes.
I tried to copy the text file and paste it somewhere else for my
program to read, this way I definitely have full access to it and
once I am done with it, Ill delete it. This gave me nothing to print
aswell.
Am I right to deduce that it is always giving me EOF thus this is
having problems.
while ((result = fscanf(readLOG_fp, "%[^\n]\n", ReadLogLine)) != EOF) // Loops through the file till it reaches the end of file
If yes, How do I fix this?? What other ways can I make it read every line. I have seriously exhausted all my ideas on this problem and need some help in this.
Thanks everyone for your help.
Error is very obvious ... you might have over looked it..
You forgot to open the file.
FILE *readLOG_fp;
CString LogPathName;
LogPathName = Source_Folder + "\\serco.log";
readLOG_fp = fopen(LogPathName.GetBuffer());
if(readLOG_fp==NULL)
cout<<"Error: opening file\n";

Reading file line by line with C++ always output 2 lines even if file is different

I need to store each lines of a text document into a vector. However any file text I try, the output is always 2 lines. First one is empty and second one always output: "DONE". I'm on Windows7 X64, using VC++2013.
I have been trying to solve this for many hours. I tried many different approach but the result stay the same. I suspect that "DONE" is the return value from getline() however I don't understand with my code is not working like it should.
int main() {
ifstream hFile("test.txt");
vector<string> lines;
string line;
while (std::getline(hFile, line))
lines.push_back(line);
cout << lines[1];
hFile.close();
getchar();
return 0;
}
EDIT: It works fine when executing the program from the compilation folder but not in the debug console of VC++...
The program looks mostly correct. The only problem is that your code assumes that there are, at least, two lines in your file: if there are few lines, e.g., just one or the files couldn't be opened, the statement
cout << lines[1];
result in undefined behavior. Did you mean to print each line of the file rather than just the second line?
From the description of the behavior I would suspect that you file either contains the string DONE or you are actually executing a different program!
Be careful, it proves nothing about the count of lines:
cout << lines[1];
Use line.size() to count the read lines. In fact for a file with one line, it's undefined behavior to access second item.