understanding ifstream objects and reading from files - c++

I'm just learning and practicing the basics of ifstream objects and tried to write a small program that will read a .txt file and then display what is read. I can't tell what I need to change, but i do know that there might be something wrong with how I'm specifying the path because. When I run the program, it doesn't seem like it can open the file. the friends.txt file I made is in the path I specified. In the .txt file, there are 3 names which are written on 3 consecutive lines (after typing one name, I pressed enter to write another name on a new line).
I tried checking to see if made any typos on the folder names in the path and made sure to correct any I found.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream inputfile;
string name;
inputfile.open("C:\\Users\\Dox\\Documents\\Visual Studio 2015\\Projects\\Practice\\Practice\\friends.txt");
cout << "Reading data from the file.\n";
if (!inputfile.is_open())
{
cout << "error opening file" << endl;
}
else
{
inputfile >> name;
cout << name << endl;
inputfile >> name;
cout << name << endl;
inputfile >> name;
cout << name << endl;
}
inputfile.close();
cin.get();
return 0;
}
When running the code, the error message I made displays.

Related

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;
}

ifstream + opening random txt file (c_str)

I want to open a random .txt file and put the data into some strings.
It works if I write the path into the code.
I don't get it why this doesn't work.
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
string file;
ifstream filein(file.c_str());
cout << "Insert Path" << endl;
cin >> file;
cout << file << endl;
filein.open(file.c_str(), ios::in);
for (string line; getline(filein, line);) {
cout << line << endl;
}
return 0;
}
Your filename string is empty because std::string defaults to empty.
You are passing an empty string (or the nul string) to the ifstream constructor, which is at best, undefined behavior.
Try writing your code like this:
#include <iostream>
#include <fstream>
int main()
{
std::string file;
std::cout << "Insert Path" << std::endl;
std::getline(std::cin, file);
std::cout << file << std::endl;
std::ifstream filein(file);
for (std::string line; std::getline(filein, line); )
{
std::cout << line << std::endl;
}
return 0;
}
Notable edits include:
We're now constructing the ifstream object only when we need it, after file has had data stored, which means no more undefined behavior, and that we only attempt to open a file after we know what the path is.
We're retrieving a whole line when storing to file, instead of only the first word, which is crucial if your path includes any spaces.
We're just using the file string directly. There's no need to call c_str().
We're no longer using using namespace std;. There are many, many reasons why this is bad practice.
EDIT:
If you have a C++17-compliant compiler, I'm going to propose you write code that looks like this instead:
#include <iostream>
#include <fstream>
//You may need to write #include <experimental/filesystem>
#include <filesystem>
#include <string>
int main()
{
std::string input_line;
std::cout << "Insert Path" << std::endl;
std::getline(std::cin, input_line);
//You may need to write std::experimental::filesystem
std::filesystem::path file_path{input_line};
//This will print the "absolute path", which is more valuable for debugging purposes
std::cout << std::filesystem::absolute(file_path) << std::endl;
std::ifstream filein(file_path);
for (std::string line; std::getline(filein, line); )
{
cout << line << endl;
}
return 0;
}
Explicit use of path objects will make your code more readable and make errors more explicit, as well as grant you access to behavior you otherwise would not be able to access.
first what are you opening? as long as you string doesn't contain anything??
second even if the string contains a valid path and the opening was successfull at the first time but in the second will fail as long as you use the same file stream on multiple files without clearing its buffer and closing the previous file:
string file "C:\\MyProject\\data.txt"; // let's say a valid path
ifstream filein(file.c_str());
if(filein.fail()) // the condition fails as long as the opening was successfull
cout << "failed to open file!" << endl;
cout << "Insert Path" << endl;
cin >> file; // let's say the user enters a valid path again: "C:\\MyProject\\test.txt"
cout << file << endl;
filein.open(file.c_str(), ios::in); // fail to correct it:
filein.close();
filein.clear(); // very important
filein.open(file.c_str(), ios::in); // now it's ok!
for (string line; getline(filein, line);) {
cout << line << endl;
}

Simple C++ file reading program only returns garbage

I'm a beginner programmer and I'm having an issue that I'm sure is just caused by a stupid mistake but I for the life of me can't figure out what it is. I've tried searching solutions on this site but none of the remedies I found worked for my problem
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream inputFile;
float num;
inputFile.open("numbers.txt");
inputFile >> num;
cout << num << endl;
inputFile >> num;
cout << num << endl;
inputFile >> num;
cout << num << endl;
inputFile >> num;
cout << num << endl;
inputFile >> num;
cout << num << endl;
inputFile.close();
return 0;
}
So it's a simple code, and I'm reading the textbook I have verbatim on what to do but whenever I run the code it just churns out garbage versus the numbers.txt file I created using a different program.
If anyone can tell me where my mistake is, or tell me where to look up this problem I'd appreciate it. Thanks in advance
Edit: I used a different code to create the file and I can confirm that the file was created successfully in .txt format
Please check if the file is opened correctly. Add the below code after inputFile.open("numbers.txt");
if(inputFile.fail())
{
cerr<< "Error Opening File" << endl;
exit(1);
}
Also try giving the absolute path of the file if there is an error in opening the file.

infile won't open in c++ on mac

Hello I am following a tutorial on youtube that is beginning with in files and out files.
This is my code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream infile;
infile.open("numbers.rtf");
//Check for Error
if (infile.fail())
{
cerr << "Error opening file" << endl;
exit(1);
}
int x, y;
infile >> x >> y;
cout << "num 1 =" << x << endl;
cout << "num 2 =" << y << endl;
return 0;
}
I am running on a mac so the .txt file is .rtf. Even after changing that extension the error message still comes up. Heading to school now, appreciate responses
Your code is correct. Has nothing to do with the type of file you are opening.
In case you are compiling from command line, place the file number.rtf in the same folder from which you're launching your executable, and it should find the file.
Otherwise, use a full pathname for the .rtf file.
PS: You can use a .txt file extension on a mac as well. .rtf is just the default.

How to write even numbers from sequential access file to a new sequential access files

Can someone with a little time on their hands please compile and run this code and see where I am going wrong?
#include <iostream>
#include <fstream>
using std::cout;
using std::endl;
using std::ifstream;
using std::ofstream;
using std::ios;
int main()
{
int numbers = 0;
//create and open file
ifstream inFile;
ofstream outFile;
inFile.open ("numbers.txt", ios::in);
outFile.open ("evenNumbers.txt", ios::out);
//determine whether the file was opened
if (inFile.is_open() && outFile.is_open())
{
//read numbers file
inFile >> numbers;
while (!inFile.eof())
{
//look for even numbers
if (numbers %2 == 0)
{
outFile << numbers << endl;
//cout << numbers << endl;
}
inFile >> numbers;
}
//end while
//close files
outFile.close();
inFile.close();
cout << "Program successful. File complete." << endl;
}
//if file fails to open, display error message
else
cout << " File could not be opened " << endl;
//end if
system ("pause");
return 0;
} //end of main function
Your code has quite a few problems:
ifstream inFile;
inFile.open("numbers.txt", ios::in);
It's not exactly an error, but ios::in is the default for an ifstream, and you typically supply the file name to the constructor, something like this:
ifstream inFile("numbers.txt");
Then we have this:
getline(inFile, name);
inFile >> num;
while (inFile.eof())
while (inFile.eof()) seems to have the logic backwards -- you want to read until you reach the end of the, then quit. The rest of your loop will work (unusual for one that uses file.eof() as the condition) but is unnecessarily long and difficult to read.
//create file object and open the file
ofstream outFile;
outFile.open("updatedNumbers.txt", ios::out);
As you'd expect from the previous comment, ios::out is the default for an ofstream, and you usually give the file name to the constructor: ofstream outFile("updatedNumbers.txt");
//write the updated numbers to the file
outFile << heading << endl;
outFile << columnHeaders << endl;
outFile << underLines << endl;
heading, columnHeadders and underLines seem to be undefined variables.
for (x=0;x<20; x++)
{
if (int x%2==0)
sample[x] = x+2;
else
sample[x] = x+20;
sample also seems to be undefined.
outFile << num[x] << endl;
num also seems to be undefined. Perhaps you intended it to be the same as sample? Otherwise, you don't seem to have any code to set it to any particular value before you write it out.
Probably worse than any of that is the fact that your heading talks about writing the even numbers from one file to another, but your code doesn't seem to do anything even vaguely similar to that at all.
Well, the heading variable is undeclared, but I guess you already know that....
The error is here:
outFile << heading << endl;
outFile << columnHeaders << endl;
outFile << underLines << endl;
This is the first time you these variables heading, columnHeaders and underLines are mentioned in your program. The compiler complains because they have not been declared anywhere (Should they be int or std::string ore some other type?). Also they won't contain any useful values because nothing has been assigned to them.