Can't write to txt file [closed] - c++

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 months ago.
Improve this question
I am trying to write to a .txt file within a program, and I am using the following code snippet. I want to output a line of the form:
a(space)b
but I get nothing on the txt file.
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
int main(){
string a = "string";
int b = 0;
fstream f;
f.open("filename.txt",ios::in | ios::out );
f << a << ' ' << b << endl;
f.close();
return 0;
}

If you try this piece of code:
f.open("filename.txt", ios::in | ios::out);
if (!f.is_open()) {
cout << "error";
}
you will see that the file is never opened. ios::in requires an already existing file (std::fstream::open()):
It should work if you should only pass std::ios::out to f.open():
f.open("filename.txt", ios::out);
Read here why you shouldn't be using namespace std;.

Try this version. Few changes:
Include the correct header <string> instead of <cstring>
No using namespace std;
Use std::ofstream for output
No .open(): pass the filename in the constructor
Check if the file is valid after opening
No .close(). Let the destructor do its job.
No std::endl if '\n' is enough.
#include <iostream>
#include <fstream>
#include <string>
int main()
{
std::string a = "string";
int b = 0;
std::ofstream f("filename.txt");
if (!f) {
return EXIT_FAILURE;
}
f << a << ' ' << b << '\n';
return EXIT_SUCCESS;
}

Related

Why is my C++ code with file output not working? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 months ago.
Improve this question
I didn't got any errors, but my C++ code is still not working. It's really simple:
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
string a;
ofstream fout("char.out");
ifstream fin("char.in");
fin >> a;
fout << a;
return 0;
}
char.in after running:
uiui
char.out after running:
Did I missed anything simple in my code?
P. S. : I got Norton Antivirus and my project folder is missed from AutoCheck.
in fact for reading and writing you should open and close file but you didn't close.
Also you have two files where you have done writing from one file and reading from another file, I wonder how you expect to get the correct output.
this is how it should be :
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
string a;
ofstream fout("char.out");
// check if file is created
if(fout.is_open()){
// do writing in file
}
else
cout << "can not open file\n";
fout.close();
//-----------reading the file----------
// use the same file
ifstream fin("char.out");
if(fun.is_open()){
// do reading from file
std::cout << a << std::endl;
}
else
cout << "can not open file\n";
fin.close();
return 0;
}
And if you want to add a line of text to the end of the file, you must add:
ofstream fout("filename" , ios::app);

Reading from a .txt file to a vector of doubles in C++ [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I am trying to read values from a .txt file to a vector (which is a member of a class) in C++, but despite the .txt having around 1000 lines, the vector is of size 0. I inserted a 'cout', and I know the file is opened and closed. I'm not sure what I could be doing wrong for the code not to read the contents of the .txt.
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <cmath>
#include "option_class.h"
using namespace std;
int main(){
double cprice = 0.0;
int i = 0;
string line;
ifstream is;
is.open("/Users/<USER>/Desktop/SPY.txt");
if (!is){
cout << "Unable to open file" << endl;
return(0);
}
while(!getline(is, line).eof()){
is >> cprice;
option1.price.push_back(cprice);
}
is.close();
cout << "Closing file" << endl;
}
Have you tried something simpler:
while (is >> cprice)
{
option1.price.push_back(cprice);
}
The operator>> will skip whitespace, which includes newlines. There is no need to read a line at a time.

Reading from file line by line [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I need to read from file line by line and print it on the screen:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ofstream out("note.txt");
for (int i = 0; i < 10; i++)
out << i << " " << (i<<1) << "\n";
out.close();
ifstream fin;
fin.open("note.txt");
string line;
for (int i = 0; i < 10; ++i)
{
getline(fin, line);
cout << line << "\n";
}
return 0;
}
Is this approach correct? Cant I do it without a string variable (without string line in code)?
Instead of using a for loop you can use a while loop:
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
int main() {
string line;
ifstream out("note.txt");
while(getline(out, line)) {
cout << line << endl;
}
out.close();
}
If you are forced not to use strings then you can try a char buffer char buf[1024]. It must be pointed out that this approach is dangerous and error prone. If a line has more than 1024 characters then a buffer overflow will occur. Buffer overflow is the cause of many vulnerabilities and crashes. That being said, if you really have to use this method I would suggest you to be very careful by making the appropriate checks.
Copying a file verbatim is a simple as streaming out its stream buffer:
ifstream fin;
fin.open("note.txt");
std::cout << fin.rdbuf();

C++ transform not declared in scope only occurs on server [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I've seen a lot of these but none of them seem to correspond to my problem. This program runs locally fine but on the server it needs to run on I run into an error.
project1.cpp: In function ‘void insertwords(char*)’:
project1.cpp:54:65: error: ‘transform’ was not declared in this scope
transform(word.begin(), word.end(), word.begin(), ::tolower);
the relevant code:
void insertwords(char *filename) {
ifstream fin;
fin.open(filename);
if(fin.fail())
{
cerr << "File opening failed. Exiting program.\n";
exit (-1);
}
string word;
int count = 0;
while (!fin.eof() ) {
word.clear();
fin >> word;
transform(word.begin(), word.end(), word.begin(), ::tolower);
for (int i = 0, len = word.size(); i < len; i++)
{
if(ispunct(word[i]))
word.erase(i--, 1);
len = word.size();
}
if(!word.empty()) {
insert_word(word);
++count;
}
}
cout << "The number of words found in the file was " << count << "\n";
fin.close();
}
Includes:
#include <iostream>
#include <string>
#include <fstream>
#include <cctype>
#include <locale>
using namespace std;
I know using namespace std; is bad practice but I was told to for the project
You need to #include <algorithm> which is the header where std::transform comes from.
As to why it would compile on one machine and not another, my guess would be that one of your other headers (e.g. <string>) includes <algorithm> in one of the compiler implementations so you got lucky, but not for the other compiler.

Reading from a txt file in class constructor [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I want to test constructor's functionality and an interesting problem was encountered. After compiling that code i get the linking error LNK2019 referencing to main(). How to be able to read and copy the content of one.txt line by line in my case? I'm referring to the book "Thinking in C++" ex 7.01 but since working with Visual Studio I cannot use main(int argc, char* argv[]) version..
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
class Text
{
string text;
public:
Text();
Text(const string& name)
{
ifstream infile;
infile.open(name);
if(!infile.good())
{
cout << "File is not open";
}
else
{
string line;
while(getline(infile,line))
text = text + line + '\n';
}
};
string contetns()
{
return text;
};
};
int main()
{
Text o1;
Text o2("one.txt");
cout << "content: " << o1.contetns() << endl;
cout << "content: " << o2.contetns() << endl;
system("pause");
}
As tmaric already says, you need an empty constructor:
//Text();
Text(){};
You have to define your empty destructor.