Why is my file not being read from the beginning? - c++

I am writing a program that needs to read in a list of 11,000 numbers from a text file and then output them to the console. However, whenever I run my code, I have been able to pinpoint that it only prints the last 299 numbers. Here is my code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
double dataVector[11000]; //text file has 11,000 elements
string userfile; //name of file selected by user
//prompt user for file to be opened
cout << "Enter the name of the file you would like to read :: ";
cin >> userfile;
ifstream ifs(userfile); //open file
if (!ifs) // return error message if file cannot be opened
{
cerr << "Error: could not find the specified file" << endl;
return 1;
}
for (int i = 0; i < 11000; i++)
{
if (ifs >> dataVector[i]) //read in array
cout << dataVector[i] << endl;
else //if element cannot be read, return error
{
cout << "Failed to read." << endl;
break;
}
}
ifs.close(); //closes the file
system("pause");
return 0;
}
Is there something that I'm missing that's causing this issue? My code is not returning any compiler errors, no errors from my checks, and my text file IS in the right location.

Related

Getline(); extraction stops with the 1A character

so I don't know how to explain this correctly but gonna try my best.
I'm trying to save a file into a string, it's not a .txt file, it's a .umsbt file so it has weird ASCII characters (like 00, 0A, 0E, 1A...) so when I save the .umsbt into the string using getline(); and then print it using cout, the whole file isn't printed, and when I open the actual file through HxD (hex editor) I see that the print stopped before a 1A character, did some tests and it's the 1A character's fault.
This is my code
#include <iostream>
#include <stdlib.h>
#include <fstream>
#include <string>
#include <string.h>
#include <conio.h>
#include <sstream>
using namespace std;
string line; //the file is stored here
string name; //name of the file
void printfile() {
int o = 0;
int fileCount;
ifstream file;
file.open(name, ios::in);
if (file.fail()) {
cout << "Not found \n";
cin.get();
cin.get();
exit(1);
}else {
file.seekg(0, ios::end);
fileCount = file.tellg();
file.seekg(0);
while (!file.eof()) {
getline(file, line);
cout << "file character count: " << fileCount << endl;
cout << "string character count: " << line.length() << "\n" << endl;
for (int i = 0; i < line.length(); i++) {
cout << line[i];
o++;
if (o == 16) {
cout << "\n";
o = 0;
}
}
}
file.close();
}
}
int main()
{
cin.ignore(26, '\n');
cout << "Write the name of your file (.umsbt included) \n" << endl;
cin >> name;
cout << "\n";
printfile();
cin.get();
cin.get();
return 0;
}
Hope someone can help me, I'm currently trying to remove/replace all of the 1A characters in any file, and the restriction is that you have to do it in the ifstream itself, cause you can't save it in a string (will cause the problem with 1A and the file won't be fully saved)
(Here's a pic of the file opened up in HxD hope you get an idea of it https://imgur.com/a/1uQzOPq)
Thank you in advance
Seems that you are using binary files and not a normal text file.
Check out these links to learn about binary files.
https://study.com/academy/lesson/writing-reading-binary-files-in-c-programming.html
https://computer.howstuffworks.com/c39.htm
Bye,
Samuel

How can I open files using filestream in Notepad++ and cmd? C++

I'm confused about how to open/access a file using Notepad++ and the cmd with MinGW compiler. I understand the file needs to be in the same scope however, I'm not sure where. I have tried placing the .txt file in my Documents folder which also holds the main.cpp file, and I have tried placing it in the bin folder of the MinGw folder. When I run the code, I get the error message. Is something wrong with my code or is the .txt file in the wrong location?
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
ifstream inFS;
ofstream outFS;
string fileName;
double fileNum;
//fileName = "input_prac.txt";
//cout << "Enter file name: " << endl;
//cin >> fileName;
cout << "Opening file..." << endl;
inFS.open("input_prac.txt"); // Open file
if (!inFS.is_open())
{
cout << "Could not open file" << endl;
exit(1);
}
// Read file
while(!inFS.eof())
{
inFS >> fileNum;
cout << fileNum << endl;
}
inFS.close(); // close file
return 0;
}

Empty content in output out from while cycle

I want to load data from .txt file to variable and working with them (like calculate). When I open data, I can read them, but I don´t know to work with data.
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;
int main()
{
fstream newfile;
string file;
newfile.open("zadanie.txt", ios::in);
if (newfile.is_open()) {
while (getline(newfile, file)) {
cout << file << "\n"; //I GET OUTPUT CORRECTLY
}
newfile.close();
}
else
cout << "Error. \n";
cout << file << "\n"; //HERE IS PROBLEM. OUTPUT IS EMPTY
return 0;
}
I tried global variable, but it not solved. What should I do to correct it? Thanks
What you call "PROBLEM" in the comment is not a problem. file never contains more than a single from the file. The last call to getline will not read a line because there is nothing left in the file when you reach its end. So when you call
std::cout << file;
after that loop, it is to be expected that file is empty. If you want to use the lines later you should store them somewhere, eg in a std::vector<std::string>> :
int main()
{
fstream newfile;
std::vector<std::string> data; // vector to hold all lines
newfile.open("zadanie.txt", ios::in);
if (newfile.is_open()) {
string line; // better name (file->line)
while (getline(newfile, line)) {
cout << line << "\n";
data.push_back(line); // add the line to data
}
newfile.close();
}
else
cout << "Error. \n";
for (const auto& l : data) std::cout << l << '\n';
return 0;
}

I/O program stuck in loop C++

I'm working on a code that reads in a C++ source file and converts all ‘<’ symbols to “<” and all ‘>’ symbols to “>”. I wrote out the main method and everything compiled nicely but now that I'm actually writing out my convert function at the top of the program, I'm stuck in an infinite loop and I'm hitting a wall on what the culprit is. Could someone help me out?
I included the whole program in case the problem lies in my I/O coding but I surrounded the function with slashes. Hopefully I won't get flamed.
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
#include <cstring>
using namespace std;
//FUNCTION GOES THROUGH EACH CHARACTER OF FILE
//AND CONVERTS ALL < & > TO < or > RESPECTIVELY
//////////////THIS IS THE FUNCTION IN QUESTION//////////
void convert (ifstream& inStream, ofstream& outStream){
cout << "start" << endl;
char x;
inStream.get(x);
while (!inStream.eof()){
if (x == '<')
outStream << "<";
else if (x == '>')
outStream << ">";
else
outStream << x;
}
cout << "end" << endl;
};
///////////////////////////////////////////////////////////////////////////
int main(){
//FILE OBJECTS
ifstream inputStream;
ofstream outputStream;
string fileName;
//string outFile;
//USER PROMPT FOR NAME OF FILE
cout << "Please enter the name of the file to be converted: " << endl;
cin >> fileName;
//outFile = fileName + ".html";
//ASSOCIATES FILE OBJECTS WITH FILES
inputStream.open(fileName.c_str());
outputStream.open(fileName + ".html");
//CREATES A CONVERTED OUTPUT WITH <PRE> AT START AND </PRE> AT END
outputStream << " <PRE>" << endl;
convert(inputStream, outputStream);
outputStream << " </PRE>" << endl;
inputStream.close();
outputStream.close();
cout << "Conversion complete." << endl;
return 0;
}
It isn't a good approach to manipulate a file while you're reading it. The right way is, first read the whole file, store the data, manipulate the stored data, and then update the file. Hope this code will help you :)
void convert()
{
int countLines = 0; // To count total lines in file
string *lines; // To store all lines
string temp;
ifstream in;
ofstream out;
// Opening file to count Lines
in.open("filename.txt");
while (!in.eof())
{
getline(in, temp);
countLines++;
}
in.close();
// Allocating Memory
lines = new string[countLines];
// Open it again to stroe data
in.open("filename.txt");
int i = 0;
while (!in.eof())
{
getline(in, lines[i]);
// To check if there is '<' symbol in the following line
for (int j = 0; lines[i][j] != '\0'; j++)
{
// Checking the conditon
if (lines[i][j] == '<')
lines[i][j] = '>';
}
i++;
}
in.close();
// Now mainuplating the file
out.open("filename.txt");
for (int i = 0; i < countLines; i++)
{
out << lines[i];
if (i < countLines - 1)
out << endl;
}
out.close();
}

Why is this loop not looping?

I need to do this: Open a user-specified file for input. Prompt for the name of the file, read it into a string variable, echo print it to the terminal and then open it. If the file is not successfully opened, enter into a loop that prints out an error message, resets the input file stream variable (Input_file_stream_var.clear(); Where Input_file_stream_var is the name of your input file stream variable), obtains a new file name and tries to open the new file. The loop continues until the user successfully enters a valid file name or presses ctrl-c to exit.
and here is the code that i have so far but i cant get it to loop back into the process if the file was not opened.
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <iomanip>
using namespace std;
int main()
{
// Variables
char test;
string infname, outfname;
fstream infile, outfile;
do
{
// Propt for and echo print input file
cout << endl << "Enter the name of the input file: ";
cin >> infname;
cout << infname << endl;
infile.open(infname.c_str());
// Test if file opened
if(!infile)
{
cout << string(12,'*') << " File Open Error " << string(12,'*') << endl;
cout << "==> Input file failed to open properly!!\n";
cout << "==> Attempted to open file: " << infname << endl;
cout << "==> Please try again...\n";
cout << string(41,'*') << endl;
infile.clear();
return 1;
}
} while(!infile.is_open());
return 0;
}
The return 1 statement is causing your program to exit: you are returning from main()
Just don't do that.
Try removing the return 1 or changing it to continue. return 1 returns code execution from main and not the loop.