I'm trying to create a simple program that accepts user input and writes it to a text file.
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main(){
string name; int score; fstream scoreSheet;
scoreSheet.open("score_sheet.txt");
string stayOpen = "y";
while(stayOpen == "y"){
scoreSheet >> name >> score;
cout << "Do you want to add another entry? (y/n) ";
cin >> stayOpen;}
scoreSheet.close();
return 0;}
When this is run no file is created in the directory except for a gmon.out. Why isn't the file created and how do I write user input to the file?
For creating file and write into that file, you have to specify mode in open function.
And also you have to scan data every time when you give Yes for write data into file.
Below is updated code.Hope this will solve your problem.
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
string name ; int score; fstream scoreSheet;
scoreSheet.open("path to ur file", fstream::out | fstream::app );
string stayOpen = "y";
while(stayOpen == "y")
{
cout<<"Enter new entry for name and score"<<endl;
cin >> name >> score;
scoreSheet << name << score;
cout << "Do you want to add another entry? (y/n) ";
cin >> stayOpen;}
scoreSheet.close();
return 0;
}
You need to do >> with cin or some file that exists. And the >> operator when used with scoreSheet should be a << since you are trying to write to a stream not reading from it. Also you should consider changing fstream to ofstream since you want to write to a file
Files are created when you open them as output, and not as input.
When you are going to read data from a file into your variables, the file should already be there (otherwise, where should the data come from?).
On the other hand, if you want to write data into your file, and therefore open it in the write mode, then the file will be created if it does not already exist.
You should use ofstream if you want the file stream to be written to. Also as others have commented, to write to the file, you need to get the content from somewhere else, like from console input or another file for input. Try the following code as a guide. Also you can take a look at fstream or any decent book on this topic (e.g., C++ Primer Chapter 8)
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main(){
string name; int score;
fstream scoreSheet("score_sheet.txt", fstream::out);
// Only proceed if file opened successfully
if (scoreSheet) {
string stayOpen = "y";
while(stayOpen == "y"){
cin >> name >> score;
fstream << name << score << "\n";
cout << "Do you want to add another entry? (y/n) ";
cin >> stayOpen;
}
scoreSheet.close();
}
return 0;
}
Related
I'm using Sublime Text 3 on mac to write c++. I wrote some code that gets my cin value for the name and the age and write them in the file file.txt.
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
string name;
int age;
ofstream file("file.txt", ios::out);
cout<<"enter name: "<<endl;
cin>>name;
cout<<"enter age: "<<endl;
cin>>age;
file<<name<<" "<<age<<endl;
return 0;
}
The problem is that "file.txt" file is stored in my home folder, not my current working directory.
how can I store it in my current working directory?
check this
That's too weird problem, I'm not 100% fully sure about macOS, but this works on Linux and Windows.
#include <iostream>
#include <fstream>
int main(void) {
std::ofstream file("./file.txt", std::ios::out); // --- here add './' prefix
std::string name;
int age;
std::cout << "Enter your name: ";
std::getline(std::cin, name); // use std::getline() for whitespaces
std::cout << "Your age: ";
std::cin >> age;
file << name << ' ' << age << '\n';
return 0;
}
Just add ./ before the file name to explicitly define the output directory of the file must the same where the program is actually running.
Another solution
If the aforementioned solution fails, try g++ -o your_program your_program.cpp and run the program again. If it works successfully as you expect, it's cleared that something's wrong in your Sublime Text settings.
This is my first project in C++. I took a course using C previously and file I/O seems to differ a little.
The project requires the user to enter a name for saving the output file.
I know I should use ofstream which should look like this:
ofstream myfile;
myfile.open ("example.txt");
myfile << "Writing this to a file.\n";
myfile.close();
I've bolded the snippet that's causing confusion.
How can I name the file from a string entered by the user?
*Note, C type string, so an array of characters.
#include < string > is not allowed
As my other answer has got a negative vote, here's another solution without #include <string>
You can just save the input from the user in a temporary char array and then save it to a string variable std::string.
Includes that are necessary:
#include <iostream>
#include <fstream>
Saving an input from an user into a char array:
char input[260];
cin >> input;
To then save it in a string variable just do this:
string filename = input;
To open a file stream you'll need to use std::ofstream. Please keep in mind, that the file is created in the same folder as the project/application is.
std::ofstream outfile (filename + "." + "file extension");
And as you already know this outfile.open(); opens the file.
With outfile << "hello"; you can write into the file.
To close the file, use outfile.close(); to close the file.
Here you have a little example code:
#include <iostream>
#include <fstream>
using namespace std;
void main()
{
char input[260];
cin >> input;
string filename = input;
ofstream outfile(filename + "." + "txt");
outfile << "hello";
outfile.close();
}
I hope this helps.
Regards.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
string path;
string name;
string h_path;
string text;
void create() {
ofstream file(h_path, ios::app);
if (!file.fail()) {
file << text;
file.close();
}
}
int main() {
cout << "please enter path(c:\\folder\): ";
cin >> path;
cin.ignore();
path = path + "/";
cout << "please enter the name of the file (test.txt): ";
getline(cin, name);
cout << "content of the file: ";
getline(cin, text);
h_path = path + name;
create();
cout << "new file created";
cout << h_path;
}
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
string fileName;
cin >> fileName;
ofstream myfile;
myfile.open(fileName);
myfile << "Writing this to a file.\n";
myfile.close();
}
I need to make a Point of Sale software which is reading product names, barcodes and prices from a given text file. I can extract all the required data from the file, but I don't know how to use that data. To be precise I need to calculate the prices of picked products. My program is currently able to ask a user for a barcode and print out the chosen products
#include <iostream>
#include <string>
#include <fstream>
#include <cstdlib>
using namespace std;
void KeyWord(ifstream &FileSearch)
{
string line;
string letters[5];
ifstream readSearch;
cout<< "Enter a barcode of a product: \n";
cin >> letters[0];
cin >> letters[1];
cin >> letters[2];
cin >> letters[3];
cin >> letters[4];
readSearch.open("Products.txt");
if(readSearch.is_open())
{
while (getline(readSearch, line))
{
while (line.find(letters[0])!=string::npos || line.find(letters[1])!=string::npos || line.find(letters[2])!=string::npos || line.find(letters[3])!=string::npos || line.find(letters[4])!=string::npos)
{
cout << line << "\n";
break;
}
}
}
}
int main()
{
ifstream file("Products.txt");
KeyWord(file);
return 0;
}
If each line contains a set of product names, barcodes and prices, get the line into an std::stringstream and move on from there.
sorry im real new to c++ and can't seem to understand the basic concept of reading a txt file and writing one. i have a program that currently just prompts the users and then delivers the output on the command line after reading the data. but i want to have it read a file, and the create a file with its output
heres it so far
#include <iostream>
#include <string>
using namespace std;
int main()
{
cout << "Enter number of names \n";
int a;
cin >> a;
string * namesArray = new string[a];
for( int i=0; i<a; i++) {
string temp;
cin >> temp;
namesArray[i] = temp;
}
for( int j=0; j<a; j++) {
cout << "hello " << namesArray[j] << "\n";
}
return 0;
}
Thanks to all..
#include <fstream>
#include <string>
#include <iostream>
using namespace std;
int main(){
string fileName = "test.txt";
//declare a file object
//options are:
//ofstream for output
//ifstream for input
//fstream for both
fstream myFile;
//cannot pass a c++ string as filename so we convert it to a "c string"
//... by calling strings c_str member function (aka method)
//the fstream::out part opens the file for writing
myFile.open(fileName.c_str(), fstream::out);
//add the text to the file end the line (optional)
myFile << "Some text" << endl;
myFile.close();//always close your files (bad things happen otherwise)
//open the file for reading with fstream::in
myFile.open(fileName.c_str(), fstream::in);
string myString;
//get a line from a file (must be open for reading)
getline(myFile,myString);
myFile.close();//always close your file
//demonstrates that it works
cout << myString;
}
This a sample of reading a file or This example to write to a file to do what you are asking, if you want to know what are you doing, the << and >> operators, are like water valve that let you move the stream of information from side to side, "cin" is a "data generator", from keyboard, in the example in the page, "myReadFile.open" make a "data generator" from an input file, and you move that data using >> to save it to a string and << to move it to cout, dont know if it help you understand a little more of C++ streams...
ifstream input;
input.open("inputfile.txt");
input >> var; //stores the text in the file to an int or string
input.close();
ofstream output;
output.open("outputfile.txt"); //creates this output file
output << var; //writes var to the output file
output.close();
hope that helps
Hey everyone, I have just started to learn C++ and I wanted to know how to read and write to a text file. I have seen many examples but they have all been hard to understand/follow and they have all varied. I was hoping that someone here could help. I am a total beginner so I need clear instructions. Here is an example of what i'm trying to do:
#include <iostream>
#include <fstream>
using namespace std;
string usreq, usr, yn, usrenter;
int start ()
{
cout << "Welcome..."
int main ()
{
cout << "Is this your first time using TEST" << endl;
cin >> yn;
if (yn == "y")
{
ofstream iusrfile;
ofstream ousrfile;
iusrfile.open("usrfile.txt", "w");
iusrfile >> usr;
cout << iusrfile;
iusrfile.close();
cout << "Please type your Username. \n";
cin >> usrenter;
if (usrenter == usr)
{
start ();
}
}
else
{
cout << "THAT IS NOT A REGISTERED USERNAME.";
}
return 0;
}
Header files needed:
#include <iostream>
#include <fstream>
declare input file stream:
ifstream in("in.txt");
declare output file stream:
ofstream out("out.txt");
if you want to use variable for a file name, instead of hardcoding it, use this:
string file_name = "my_file.txt";
ifstream in2(file_name.c_str());
reading from file into variables (assume file has 2 int variables in):
int num1,num2;
in >> num1 >> num2;
or, reading a line a time from file:
string line;
while(getline(in,line)){
//do something with the line
}
write variables back to the file:
out << num1 << num2;
close the files:
in.close();
out.close();
Default c++ mechanism for file IO is called streams.
Streams can be of three flavors: input, output and inputoutput.
Input streams act like sources of data. To read data from an input stream you use >> operator:
istream >> my_variable; //This code will read a value from stream into your variable.
Operator >> acts different for different types. If in the example above my_variable was an int, then a number will be read from the strem, if my_variable was a string, then a word would be read, etc.
You can read more then one value from the stream by writing istream >> a >> b >> c; where a, b and c would be your variables.
Output streams act like sink to which you can write your data. To write your data to a stream, use << operator.
ostream << my_variable; //This code will write a value from your variable into stream.
As with input streams, you can write several values to the stream by writing something like this:
ostream << a << b << c;
Obviously inputoutput streams can act as both.
In your code sample you use cout and cin stream objects.
cout stands for console-output and cin for console-input. Those are predefined streams for interacting with default console.
To interact with files, you need to use ifstream and ofstream types.
Similar to cin and cout, ifstream stands for input-file-stream and ofstream stands for output-file-stream.
Your code might look like this:
#include <iostream>
#include <fstream>
using namespace std;
int start()
{
cout << "Welcome...";
// do fancy stuff
return 0;
}
int main ()
{
string usreq, usr, yn, usrenter;
cout << "Is this your first time using TEST" << endl;
cin >> yn;
if (yn == "y")
{
ifstream iusrfile;
ofstream ousrfile;
iusrfile.open("usrfile.txt");
iusrfile >> usr;
cout << iusrfile; // I'm not sure what are you trying to do here, perhaps print iusrfile contents?
iusrfile.close();
cout << "Please type your Username. \n";
cin >> usrenter;
if (usrenter == usr)
{
start ();
}
}
else
{
cout << "THAT IS NOT A REGISTERED USERNAME.";
}
return 0;
}
For further reading you might want to look at c++ I/O reference
To read you should create an instance of ifsteam and not ofstream.
ifstream iusrfile;
You should open the file in read mode.
iusrfile.open("usrfile.txt", ifstream::in);
Also this statement is not correct.
cout<<iusrfile;
If you are trying to print the data you read from the file you should do:
cout<<usr;
You can read more about ifstream and its API here