I'm trying to use a while loop to ensure a file has been opened with "ifstream inputFile(fileName);". If I enter a correct file name first, the while loop condition (!inputFile) correctly evaluates to false, and is skipped. If I enter a bad file name, the while loop correctly evaluates to true and is entered. Inside the while loop, if I enter a correct file name, the value of inputFile does change from 0 to 1 (I check with a cout statement) - but the while loop doesn't stop.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(void) {
string fileName;
cout << "\nEnter a file name: ";
cin >> fileName;
ifstream inputFile(fileName);
while(!inputFile) {
cout << "File not found, please enter another file: ";
cin >> fileName;
ifstream inputFile(fileName);
// just added to check values
cout << "fileName is: " << fileName << endl;
cout << "inputFile is: " << inputFile << endl;
}
}
The probleme here is that you define 2 variables inputFile in two different scopes. The first one is evaluated in the while condition, the second one is created and destroyed at every while iteration, and never evaluated.
Consider trying:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(void) {
string fileName;
cout << "\nEnter a file name: ";
cin >> fileName;
ifstream inputFile(fileName);
while(!inputFile) {
cout << "File not found, please enter another file: ";
cin >> fileName;
inputFile.open(fileName); // <== Here is the change
// just added to check values
cout << "fileName is: " << fileName << endl;
cout << "inputFile is: " << inputFile << endl;
}
}
Related
I'm trying to build a program that will create a .txt file and store some basic data within. Currently, the setup is pretty basic, but I've run into a problem where after inputting one's full name, the terminal seems to skip the second cin statement, (cin >> number1). I'm not certain why, and if anyone sees what might be the issue here, I would really appreciate the feedback.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ofstream fout1;
int number1;
string name;
fout1.open("numbers.txt", ios::out);
if (fout1.fail())
{
cout << "Failed to open file." << endl;
exit(1);
}
cout << "Input your full name: ";
cin >> name;
cout << "Enter a value: ";
cin >> number1;
fout1 << name << endl << number1 << endl;
fout1.close();
cout << "Your file 'numbers.txt' has been created!";
}
In addition, from every source I've seen, it seems that commanding .open on a file that doesn't yet exit will create the file in question, but I'm not able to confirm this due to the previous problem. Can anyone verify that my understanding here is correct?
Thank in advance.
As user:6752050 and user:65863 said, using getline(cin, name) solved the problem. In all my tests, the input name had a space somewhere in it which was causing some messy things to go on behind the scenes when cin was looking for a string with no spaces.
Solved code should read as follows:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ofstream fout1;
int number1;
string name;
fout1.open("numbers.txt", ios::out);
if (fout1.fail())
{
cout << "Failed to open file." << endl;
exit(1);
}
cout << "Input your full name: ";
getline(cin,name);
cout << "Enter a value: ";
cin >> number1;
fout1 << name << endl << number1 << endl;
fout1.close();
cout << "Your file 'numbers.txt' has been created!";
}
I'm trying to write a code for signup / login while being able to write and read from the file. So far I am able to write in the file and asked for the users input and displayed in the file (signup).
My problem is now,
How do I do the login part, in which when the user chooses login, they are able to choose what username they want based on a selection of usernames and the input they have made while choosing the first option?
How can this information be read and displayed in the file?
Expected output for user login
Choose you username:
0:mike
1:Linda
2:Martha
Expected input from the user
your choice: "Key in choice"
So far the code displayed works, but I am not sure what to do for my next step.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
int option;
int age,height;
string name;
string database;
ofstream file_out;
ifstream file_in;
cout << " For sign up type 1" <<endl;
cout << " For log in type 2" <<endl;
cin >> option;
if ( option == 1 ) {
file_out.open("database.txt");
cout << "Input name: \n";
cin >> name;
cout << "Input age: \n";
cin >> age;
cout << " Input height: \n";
cin >> height;
//write file
file_out << name << endl;
file_out << age << endl;
file_out << height << endl;
file_out.close();
} else if (option == 2) {
//read file
file_in.open("database.txt");
cout << "choose your username: " << endl;
// input line of code
while ( getline(file_in, database));
//input line of code
cout << database << endl;
You can do something like this. Print all the usernames, but before printing out check if they are numbers with help of the stof function, if they are numbers we don't have to do anything, but if it is a string it will throw an exception, so in the catch block we print it and store it into dictionary/map for easy retrieval.
#include <fstream>
#include <iostream>
#include <map>
int main(void) {
std::fstream file;
file.open("secret.txt", std::ios::in);
std::map<int, std::string> map;
std::string username;
int count = 1;
while (!file.eof()) {
file >> username;
try {
std::stof(username);
} catch (...) {
std::cout << count << ". " << username << "\n";
map.insert(std::make_pair(count, username));
count++;
}
}
int choice;
std::cout << "Choose your username: ";
std::cin >> choice;
username = map.at(choice);
std::cout << "Your username is set to " << username;
return 0;
}
I'm practicing ifstream usage. I want the user to enter the file they want to read, in this example num1.txt specifically. I want the console to read one letter from num1.txt and output it on its own line.
I've ran the code below, and after entering "num1.txt" into the console, I get nothing back. I've tried moving around cout << num << endl; to the inner do statement, but it ends up repeating the number 10 an infinite amount.
What am I doing wrong here?
Contents in num1.txt:
2 4 6 8 10
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main() {
string fileName, cont;
ifstream inputFile;
do {
int num = 0;
int total = 0;
cout << "Please enter the file name: ";
cin >> fileName;
inputFile.open(fileName);
if (inputFile.is_open()) {
do {
inputFile >> num;
total += num;
}
while(num > 0);
if (total != 0) {
cout << num << endl;
cout << "Total is: " << total << endl;
}
}
else {
cout << "Failed to open file." << endl;
}
inputFile.close();
cout << "Do you want to continue processing files? (yes or no): " << endl;
cin >> cont;
}
while (cont == "yes");
}
Your inner do loop is not correctly validating that operator>> is actually successful before using num. It should be looking at the stream's error state after each read. The easiest way to do that is to change your do loop into a while loop that uses the result of the read as its loop condition, eg:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main() {
string fileName, cont;
ifstream inputFile;
do {
cout << "Please enter the file name: ";
cin >> fileName;
inputFile.open(fileName);
if (inputFile.is_open()) {
int num = 0;
int total = 0;
while (inputFile >> num) {
total += num;
}
inputFile.close();
cout << "Total is: " << total << endl;
}
else {
cout << "Failed to open file." << endl;
}
cout << "Do you want to continue processing files? (yes or no): " << endl;
}
while ((cin >> cont) && (cont == "yes"));
return 0;
}
Here's my code:
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
//variable init
ifstream inFile;
ofstream outFile;
string toPrint, fileName;
string var;
cout << "Enter your save file: "; cin >> fileName;//asks the file name
cout << "Searching..."<<endl;
string fileLocation = "C:\\Users\\CraftedGaming\\Documents\\" + fileName + ".txt";//locates it
inFile.open(fileLocation.c_str());
if(!inFile){//checks if the file is existent
cerr << "Error can't find file." << endl;
outFile.open(fileLocation.c_str());
outFile << "Player House: Kubo"<<endl;
outFile.close();
}
cout << "Loaded." << endl;
inFile.ignore(1000, ':'); inFile >> var; //gets the string and places it in variable named var
cout << var<<endl;
//replaces var
cout << "Enter a string: ";
cin >> var;
//saving
outFile.open(fileLocation.c_str());
outFile << "Player House: " << var;
inFile.close();
outFile.close();
}
Problem here is that I can't get the player's house named "Kubo" and place it in variable named "var". It manages to create the file in my documents and manages to change the variable in the replaces var section.
From what I understood, you need to simultaneously read and write a file. Try this code
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
string fileName;
cout << "Enter your save file: ";
cin >> fileName;
string filePath = "C:\\Users\\CraftedGaming\\Documents\\" + fileName + ".txt";
fstream file(filePath, fstream::in | fstream::out | fstream::trunc); // open modes to read and write simultaneously
string var;
if (file.tellg() == 0)
file << "Player House: Kubo\n";
file.seekg(14);
file >> var;
cout << var << endl;
file.close();
return 0;
}
I used tellg() to determine whether file is empty, you could also go with
file.peek() == ifstream::traits_type::eof();
I am writing a simple program that stores employee info into a .txt file. It is supposed to continue writing profiles infinitely until 'n' is chosen to close file. The problem is that every time i enter in a new Emp. the previous gets overwritten, can someone help me see my oversight? Thank You in advance.
#include <iostream>
#include <fstream>
#include <cstdlib> // needed for exit()
#include <string>
#include <iomanip> // needed for formatting
using namespace std;
struct
{
string Names;
string Social;
double HourlyRate;
double HoursWorked;
} employee_info;
int main()
{
char contn = 'y';
char exitf = 'n';
string filename = "employee_info.txt"; // initialize the filename up front
ofstream outFile;
outFile.open(filename.c_str());
fstream file1;
if (outFile.fail())
{
cout << "The file was not successfully opened" << endl;
exit(1);
}
{
string employee;
while (contn == 'y')
{
cout << "Please enter Employee Name \n";
getline (cin,employee_info.Names);
cout << "Please enter Employee Social Security Number \n";
getline (cin,employee_info.Social);
cout << "Please enter Employee's Hourly Rate \n";
cin >> employee_info.HourlyRate;
cout << "Please enter Hours Worked \n";
cin >> employee_info.HoursWorked;
cout << " Enter y if you would like to enter another employee. \nEnter n to write to file. : \n ";
cin >> contn;
cin.ignore();
// set the output file stream formats
outFile << setiosflags(ios::fixed)
<< setiosflags(ios::showpoint)
<< setprecision(2);
// send data to the file
}
outFile << employee_info.Names <<endl<< employee_info.Social <<endl<< employee_info.HourlyRate <<endl<< employee_info.HoursWorked << endl;
file1.open("employee_info.txt",ios::app);
}
while (exitf == 'n')
{
outFile.close();
cout << "The file " << filename
<< " has been successfully written." << endl;
return 0;
}}
Name your struct:
struct employee
{
string Names;
string Social;
double HourlyRate;
double HoursWorked;
};
Then in main, make a std::vector of these employee structs.
(#include <vector> at the top) then std::vector<employee> empvec
At the top of the while loop, create a new employee
employee temp;
At the end of the loop, push_back() your new employee with all of the data.
empvec.push_back(temp);