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();
Related
Consider the following:
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <cctype>
#include <array>
using namespace std;
int main(){
string nname;
cout << "Enter new name for file" << endl; // prompts user to enter new filename
cin >> nname;
fstream myFile;
myFile.open("example.txt", ios::in); //opens the data folder loaded
if (myFile.is_open()){
cout << "Is open now" << endl << endl;
string text;
while(getline(myFile, text,'\n')) //reads the string line from text
{
cout << text << endl;
ofstream outfile(nname);
outfile << text;
outfile.close();
}
}
return 0;
}
"example.txt" being:
5
Id,Age,math,science,malay
2
1201101128,20,30,12,30
1201101127,33,44,66,11
The new file only has the "1201101127,33,44,66,11" line and does not contain the other lines.
I've read that the "while" loop is making it so that it reads all of the lines one-by-one, but only outputs the last one. My question is, how do you make it so that it outputs all of the lines?
You are opening the file in the while loop each time. Open the file before the loop and close it after the loop.
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <cctype>
#include <array>
using namespace std;
int main() {
string nname;
cout << "Enter new name for file" << endl; // prompts user to enter new filename
cin >> nname;
fstream myFile;
myFile.open("example.txt", ios::in); //opens the data folder loaded
if (myFile.is_open()) {
cout << "Is open now" << endl << endl;
string text;
ofstream outfile(nname);
while (getline(myFile, text)) //reads the string line from text
{
cout << text << endl;
outfile << text << endl;
}
outfile.close();
}
return 0;
}
I've been struggling all day with this problem. I can't make my program to delete an specific line of my file. I have a list of names in my file and I would like to delete one of them, I don't know what I'm missing.
EDIT: Here is my code:
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <stdlib.h>
using namespace std;
string fname;
string keyword;
int phone_num;
ifstream myfile;
ofstream phone;
void Add()
{
ofstream phone("number.txt", ios::app);
cout << "Enter Name: ";
cin >> fname;
cout << "Enter Phone Number: ";
cin >> phone_num;
if (phone.is_open())
{
phone << fname << endl;
phone << phone_num << endl;
cout << "Contact saved successfully!" << endl;
}
phone.close();
}
void All()
{
ifstream myfile("number.txt", ios::in);
while(myfile >> fname >> phone_num)
{
for(auto name : fname)
{
cout << name;
}
cout << endl;
}
}
void Delete()
{
ifstream myfile("number.txt", ios::in);
cout << "Enter Name to delete : ";
cin >> keyword;
while(getline(myfile, keyword))
{
fname.replace(fname.find(keyword),keyword.length(),"");
}
}
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;
}
}
I'm trying to have this program append a text file, making it a new line with every iteration.
It will append every time, but not add new lines for each new line.
Afterwords, I am trying to have it read out every line in the text file, though it will not read anything but the first word, and display that.
That's what I've done so far:
#include<iostream>
#include<string>
#include<fstream>
#include<ios>
using namespace std;
/*
Return types: void
Types: 1 string, 1 int
Purpose: write to the highscores.txt
*/
void Write_Score(string name, int score);
/*
Return type: Void
Types: N/A
Purpose: Read the highscores.txt
*/
void Read_Score();
int main()
{
string usr_name;
int usr_score = 0;
cout << "Enter your name: ";
cin >> usr_name;
cout << endl;
cout << "Enter your score: ";
cin >> usr_score;
cout << endl;
Write_Score(usr_name, usr_score);
cout << endl << endl << endl;
Read_Score();
}
void Write_Score(string name, int score)
{
ofstream outfile;
outfile.open("Highscores.txt", ios::app);
outfile << name << "\t" << score;
outfile.close();
}
void Read_Score()
{
string name;
int score = 0;
ifstream infile;
infile.open("Highscores.txt", ios::in);
infile >> name >> score;
cout << name << "\t" << score << endl;
infile.close();
}
You need to specify that you want a new line to be appended:
void Write_Score(string name, int score)
{
ofstream outfile;
outfile.open("Highscores.txt", ios::app);
outfile << name << "\t" << score << std::endl;
outfile.close();
}
To read a whole line you can use getline (http://www.cplusplus.com/reference/string/string/getline/).
And to read the whole file you need to loop until you reach the end of the filestream.
Read file line by line this thread will help you with that.
I'm working on a simple c++ script and wanted to put the whole process of opening up a file inside a function. However, when I try, I get errors in my main function. Can anyone help me? This is my code:
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;
string openFile(string fileName);
int main(void)
{
string fileName;
cout << "Please input the file name (including the extension) for this code to read from." << endl;
cin >> fileName;
openFile(fileName);
fout << "File has been opened" << endl;
return 0;
}
string openFile(string fileName)
{
ifstream fin(fileName);
if (fin.good())
{
ofstream fout("Output");
cout << fixed << setprecision(1);
fout << fixed << setprecision(1);
//Set the output to console and file to be to two decimal places and
//not in scientific notation
}
else
{
exit(0);
}
}
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;
ofstream fout;
string openFile(string fileName);
void closeFile();
int main(void)
{
string fileName;
cout << "Please input the file name (including the extension) for this code to read from." << endl;
cin >> fileName;
openFile(fileName);
if (fout.good()) //use fout in any way in this file by cheking .good()
cout << "File has been opened" << endl;
closeFile();
return 0;
}
string openFile(string fileName)
{
cout << fixed << setprecision(1);
fout.open(fileName.c_str());
if (fout.good()) {
fout << fixed << setprecision(1);
cout<<"Output file opened";
}
}
void closeFile()
{
fout.close();
}
Your code has lot many flaws,
fout << "File has been opened" << endl;, should be,
cout << "File has been opened" << endl;
You cannot redifine same varible again.
ofstream fout("Output");// first
cout << fixed << setprecision(1);
fout << fixed << setprecision(1);
//Set the output to console and file to be to two decimal places and
//not in scientific notation
ofstream fout("Tax Output.txt");//second
Give some other name to variable in last line.
You are passing std::string, where you should pass const char *,
ifstream fin(fileName);
should be,
ifstream fin(fileName.c_str());