I'm writing a code to open a file entered by the user and to display the file.
However, no matter how many times I read over my book I can't seem to
tell why my file is still not opening. I even copied someone else's code
that worked and mine still won't open. Someone please help me I've tried
everything.
Here is part of my code, the void function works perfectly fine and so
does the input validation, but when I open the file nothing is displayed
void readFile(int list[], int size)
{
//Identify variables
ifstream inFile;
string fileName;
cout<<"Please enter filename: ";
cin>>fileName;
inFile.open(fileName.c_str());
while(!inFile)
{
cout<<"Invalid file name. ";
inFile.clear();
inFile.ignore(200,'\n');
cout<<"Please enter filename: ";
cin>>fileName;
inFile.open(fileName.c_str());
}
For some reason everything else seems to work fine but the file will not display anything when it is opened, instead the program closes.
That's strange: this code works fine for me.
#include <cstdio>
#include <cstring>
#include <fstream>
#include<iostream>
using namespace std;
int main ()
{
// Identify variables
ifstream inFile;
string fileName, str;
cout << "Please enter filename: ";
cin >> fileName;
inFile.open(fileName.c_str());
while(!inFile) {
cout << "Invalid file name. ";
inFile.clear();
inFile.ignore(200,'\n');
cout << "Please enter filename: ";
cin >> fileName;
inFile.open(fileName.c_str());
}
while (std::getline(inFile, str)) {
cout << str;
}
cout << endl;
return 0;
}
The problem is probably with what you do with inFile after opening it.
Related
So, I am trying to implement a function that can read a file and save some variables to it. The text file will look like this
- Account Number: 12345678
- Current Balance: $875.00
- Game Played: 2
- Total Amount Won: $125.00
- Total Amount Loss: $250.00
So far, I am able to read the account number but when I try to read the rest using the same method, nothing gets outputted to the console.
Here is my progress so far.
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream inFile;
int accNum;
string accID;
int games;
double balance;
double amountWon, amountLost;
// Check if file with account number exists
cout << "Please enter account number: ";
cin >> accNum;
// Append correct format to string
accID.append("acc_");
accID.append(to_string(accNum));
accID.append(".txt");
// Open the file
inFile.open(accID);
// Check if the account number exists
if (!inFile)
{
cout << "Account number does not exist.\n";
}
int num;
string str, str2, str3;
// Read through the file
while (inFile >> str >> str2 >> str3 >> num)
{
cout << num << " ";
}
return 0;
}
When I run this code, I can get the account number to be output, but when I try adding more variables to read through the rest of the file nothing gets output to console.
You can use std::getline to read the rest of the file as shown below:
#include <fstream>
#include <string>
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
int accNum;
string accID;
int games;
double balance;
double amountWon, amountLost;
// Check if file with account number exists
cout << "Please enter account number: ";
cin >> accNum;
// Append correct format to string
accID.append("acc_");
accID.append(to_string(accNum));
accID.append(".txt");
std::cout<<accID<<std::endl;
// Open the file
ifstream inFile(accID);
if(inFile)
{
std::string strDash,strTitle, strNumber;
int num;
// Read through the file
while (std::getline(inFile, strDash, ' '),//read the symbol -
std::getline(inFile, strTitle, ':'), //read the title(for eg, Account number,Current Balance etc)
std::getline(inFile, strNumber, '\n')) //read the number at the end as string
{
std::cout<<strDash<<" "<<strTitle<<strNumber<<std::endl;//print everything read
}
}
// Check if the account number exists
else
{
cout << "Account number does not exist.\n";
}
return 0;
}
The output of the program can be seen here.
Hey I have several Files that I want to read. The user would input what file they want to open on console. And if they want they can change and read another file, they would do so.
This is how i went by doing (this is just rough copy, the code i have is too big will take too long to understand)
#include <string>
#include <iostream>
#include <vector>
#include <fstream>
#include <iomanip>
#include<algorithm>
using namespace std;
int main()
{
string FileName;
string Line;
cout << "Input File Directory To Open :" << endl;
cin >> FileName;
ifstream File;
File.open(FileName);
string Input;
do {
cout << "Enter R to Read Display Data In File Or C to Read Another File Or X To Exit" << endl;
cin >> Input;
if (Input == "R")
{
while (getline(File, Line))
{
cout << Line;
}
}
else if (Input == "C")
{
string FileName2;
cout << "Enter New File Directory To Open: " << endl;
cin >> FileName2;
//? ? ? ?
}
} while (Input != "X");
}
Since it's in do while loop, when user input C and input directory to read another file, so that they can cout new file when they input R next.
My question is how should i overwrite the FileName2 with FileName?
Hope It makes sense Thank you
First close the file that is already open:
File.close();
Then open the new one:
File.open(FileName2);
Both answers keep your idea of an open file handle. However, a better approach is to use RAII. In that case you only register the file name and only open the file when you need it.
int main()
{
std::cout << "Input File Directory To Open :\n";
std::string fileName;
std::cin >> fileName;
while (true) {
std::cout << "Enter R to Read Display Data In File Or C to Read Another File Or X To Exit\n";
std::string input;
std::cin >> input;
if (input == "X") break;
if (input == "R") {
std::ifstream file(filename);
std::string line;
while (std::getline(file, line)) {
std::cout << line;
}
// due to RAII the file will close when the object goes out of scope
} else if (input == "C") {
std::cout << "Enter New File Directory To Open: \n";
std::cin >> fileName;
}
}
}
You don't need a new variable. Simply assign the value to the existing one, close the currently opened file, and then open the new file inside the loop:
...
else if (Input == "C")
{
cout << "Enter New File Directory To Open: " << endl;
cin >> FileName;
File.close();
File.open(FileName);
}
...
I have this file with information from the periodic table in a .txt file and Im trying to write a program that allows the user to input the element symbol then read through the file until it finds that symbol and spits out information about that element. At first I got the program to output the cout statement with no information, and now its completely skipping this section after the symbol is entered and going right to the next. Here is my code.
ifstream fin;
ofstream myfile;
string line;
myfile.open("txt file");
fin.open("txt file", ios::app);
while (std::getline(fin, line)) {
fin >> element >> symbol >> atomic_number >> atomic_mass >> physical_state >> density >> melting_point >> boiling_point >> created >> chemical_group >> electronegativity;
if (line == symbol)
{
cout << "information from above"
break;
}
fin.close();
myfile.close();
}
Trying to read a .txt file and pull out a specific line based off of a letter entered by user.
Here is a sample code:
#include <iostream>
#include"string"
#include <fstream>
using namespace std;
int main(void)
{
ifstream fi("1.txt", ofstream::in);
ofstream fo("2.txt", ofstream::out);
string buf;
string s1;
cin >> s1;
while (fi >> buf)
{
if (buf.find(s1) != string::npos) break;
}
fo << buf << endl;
fi.close();
fo.close();
return 0;
}
1.txt is the file you are trying to read. Save the pull out specific line to 2.txt. "s1" is the string entered by the user.
Hope this code is helpful to you.
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.
I'm working on this program that is supposed to read data from a file that is formatted like the following, Code#Salary. The user is supposed to give a code, the program should find that code in the file if it exists and then return the salary. However, when I run the program, I keep getting a salary that is not even one of the options.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
int code;
double salary;
int name;
ifstream inFile;
inFile.open("/Users/rsoni613/Desktop/payroll.txt");
if (inFile)
{
cout << "Enter payroll code: ";
cin >> code;
do
{
inFile >> name;
}
while (code != name);
inFile.ignore('#');
inFile >> salary;
inFile.close();
cout << "Salary: $" << salary << endl;
}
else
{
cout << "File did not open, please retry.";
}
return 0;
}
Here are the contents of input file, payroll.txt
1#23400
4#17000
5#21000
6#12600
9#26700
10#18900
11#18500
13#12000
15#49000
16#56500
20#65000
21#65500
22#78200
23#71000
24#71100
25#72000
30#83000
31#84000
32#90000
double salary;
variable salary is of type double. No wonder you are getting different result.