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 5 years ago.
Improve this question
I am currently reading a book that is teaching me about C++ and I have run into a problem. I looked around the Internet a bit to see if I can find an answer but I don't seem to understand them to well. I wrote this code...
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main() {
// Writing the poem
string poem = "\n\tI never saw a man who looked";
poem.append("\n\tWith such a wistful eye");
poem.append("\n\tUpon that little tent of blue");
poem.append("\n\tWhich prisoners call the sky");
// More stuff
ofstream writer("poem.txt");
if(!writer) {
cout << "Error opening file for output" << endl;
return -1; // Signal a termination
}
writer << poem << endl;
writer.close();
// Teminates the program
return 0;
}
I think the problem specifically is this line writer << poem << endl;. But I am not sure what it is I am doing wrong. I am fairly certain I did the exercise correct.
Let me restate my issue. I have a text file that is generated with a poem. What I am trying to do is output the lines of text in the file to the console (terminal). The book that I am reading to do writer << poem << endl;. I did that but nothing is output, it just generates the file with the text and thats it.
A few long moments later.
As it turns out I was just being dumb and I later realized that the problem was more of me not reading/understanding the text to it's fullest. I was under the impression that this code was meant to output the text. I was wrong, but the following answer really helped me! Thanks.
Class ofstream writes to files not to the screen so to get the content of the file to your program then use class ifstream.
In your program if you want the text to be written to a file then read back to your program:
add this code right after closing the file after writting writer.close():
ifstream inFile("poem.txt");
string sLine;
while(getline(inFile, sLine))
cout << sLine << endl;
inFile.close();
Or simply use an object of class fstream doing the two tasks once: writting/reading.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
my goal is to create a .txt file like this:
598.1 # temperature in Kelvin
3.49 # pressure in atm
H_g # list of species allowed in the system
H2_ref
but, the first 2 values should be 2 double values, which i am using in my program
i'am using c++
If anyone has got a solution or hints for me?
That would be awesome!
Thank you in advance!
best regards
schwing
This should write your double to a text file. For more information read http://www.cplusplus.com/doc/tutorial/files/
// basic file operations
#include <iostream>
#include <fstream>
void writeFile() {
double myTempInK = 0;
double myPresInAtm = 0;
ofstream myfile;
myfile.open ("example.txt");
myfile << myTempInK << "# temperature in Kelvin\n";
myfile << myPresInAtm << "# pressure in atm\n";
myfile << "H_g # list of species allowed in the system\n";
myfile << "H2_ref \n";
myfile.close();
}
To insert data and create the file use std::ifstream f; and open it then write to it using f.write(...);
#FreshD and Graham Best:
thanks a lot...now it is working properly with this code:
std::ofstream myfile;
myfile.open("C:/Users/schwing/temp/example.txt");
myfile << p << "\n " << T << "asdf";
myfile.close();
just one question is left:
i had to specify the exact file directory. Where is the program puting the file, if i'm not using C:/Users/schwing.... and is there a possibility to use "relative" paths?
i have to mention, that i am generating a dll, and running the program in another program!
thanks in advance!
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 5 years ago.
Improve this question
I want to continue reading Stroustrup PPUC++, but I'm stuck! I wrote a BleepOutTheBadWords program a few days ago and it worked. I tried to write the program with my younger brother a few days ago and I failed. This is essentially a program I wrote to figure out what is going wrong. It is not printing out each word in the "sentence" vector.
#include <iostream>
#include "std_lib_facilities.h" // Stroustrup header file
using namespace std;
int main()
{
cout << "Write a sentence." << endl;
vector<string> sentence;
// Put user input into "sentence" vector
for (string word; cin >> word; )
sentence.push_back(word);
// Print each word in "sentence" vector
for (int i = 0; i < sentence.size(); ++i)
cout << sentence[i] << endl;
// Keep window open and return 0 to show program succeeded
keep_window_open();
return 0;
}
The answer is going to be obvious. Please just state the obvious if you are so kind. I looked through the suggested readings on two different pages before posting this.
XCode won't run my for loop
Your loop is running. The thing that you missed is how to terminate the loop.
for (string word; cin >> word; )
This loop will terminate when cin >> word evaluates to false. Normally, i.e. without an error condition, it will evaluate to false when your input is finished. The exact process to signal an end of stream, or EOF, is platform dependent. If you are running this program on OSX then the most common way to signal EOF is to hit Ctrl + D button, unless you changed the default configuration of your keyboard. Once you signal EOF this input loop will terminate and you will be able to see the output.
I'm pretty much sure that Stroustrup discussed this on his book (though I can not refer to an exact page number). However "Chapter 10: Input and Output Streams" of his books covers these things in detail.
This question already has answers here:
How to append text to a text file in C++?
(5 answers)
Closed 7 years ago.
I have created a code writing stuff in a .txt file and read from it. But if I close the program and start to write again, it deletes the old text and overwrites it with the new one.
Is there a way to not overwrite existed data?
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void check() {
string text;
ifstream file;
file.open("test.txt");
getline(file, text);
if (text == "") {
cout << "There's no data in file" << endl;
} else {
cout << "File contains:" << endl;
cout << text << endl;
}
}
int main() {
check();
string text;
ofstream file;
file.open("test.txt");
cout << "Type some text" << endl;
getline(cin, text);
file << text;
return 0;
}
You need to open the file in 'append' mode like in the following example
#include <fstream>
int main() {
std::ofstream outfile;
outfile.open("yourfile.txt", std::ios_base::app);//std::ios_base::app
outfile << "your data";
return 0;
}
You can read here about fstream flagshttp://www.cplusplus.com/reference/fstream/fstream/open/
Keep in mind that in c++ there are several ways to open, save, and read text data to and from a file. It sounds like you opened with with a function (and its options) to always create a new file. One thing you could do is run your program and then close the program and use a text editor to open the file to verify whether the text you wrote to the file is actually there. Also take a look at the code that was provided by Evyatar. That example uses ofstream which allows options for read, write, and append. The "app" parameter tells the program to keep what is already in the file and append any new data that you add in the next run. When testing files where you are appending, be careful you don't end up with a huge file you did not intend to have so large.
In the code that you posted in your revised question, be sure to close the file in your check function and at the end of the program. It is possible to get things hung up if you don't. As a precaution, I usually close a file prior to opening it, just to be sure it is closed with no problems. This practice comes form my days programming in BASIC where it was an essential. If the program crashed, you couldn't open it again until you got it closed. Also, of course, close the file after you're done with it and before the end of the program. Then, when you open it in main, open with the append option.
Please, insert code for next time. If you open file in write mode, than is normal that every time you write to file, the content of file is changed. You need to use append mode.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Improve this question
i gotta read data in c++ from a text file stored in computer
and then tokenize the data on the basis of space so that each word becomes a separate string
i have tried a code but it doesn't print anything as an output instead of a black blank screen
// basic file operations
#include <iostream.h>
#include <fstream.h>
#include <conio.h>
//using namespace std;
int main ()
{
ofstream myfile;
myfile.open ("example.txt");``
myfile << "Writing this to a file.\n";
// myfile.close();`
getch();
return 0;
}
please help :(
The code you have posted does not attempt to write anything to standard output (std::cout). It opens a file (example.txt) and writes "Writing this to a file" in it, closes the file, and then waits for you to press a button before exiting the program. You are seeing no output because you've provided no output operations, nor does it attempt to read anything from the file.
First use ifstream since you want this file as input not output
Second what is this code you posted has to do with the question?
Try this:
#include <string>
#include <iostream>
#include <fstream>
int main()
{
std::ifstream file("example.txt");
if (file.is_open())
{
std::string str;
while (std::getline(file, token, ' '))
{
//here str is your tokenized string
}
} else
{
std::cout << "Unable to open file";
}
}
getline will get the next string until the end of line or ' ' is met
This code WRITES to a file...maybe there's a C++ way to do it but strtok does what you describe.
Found within a minute of googling :)
using namespace std;
string STRING;
ifstream myReadFile;
myReadFile.open("Test.txt");
char output[100];
if (myReadFile.is_open())
{
while (!myReadFile.eof())
{
getline(myReadFile,STRING);
cout << STRING;
}
myReadFile.close();
}
Edit: Fixed the thing and tested it with success.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I've got a class:
class DataBase{
private:
fstream db_file;
public:
DataBase(){
db_file.open("db.txt", std::ios::in | std::ios::out);
}
void couteverything(){
string line;
if(db_file.good() && db_file.is_open()){
getline(db_file, line);
cout << line;
cout << "ok";
}
}
~DataBase(){
db_file.close();
}
};
and a file db.txt with some content.
I'd like to cout it to the console, but it's not working - as if the file was empty (nothing appears on the screen).
In your constructor, you do not test whether the file opened successfully. Therefore, you have no idea if the file opened successfully. Thus, your couteverything method can't distinguish EOF from "failed to open." You might consider adding a check:
DataBase(){
db_file.open("db.txt", std::ios::in | std::ios::out);
if (!db_file.is_open() || !db_file.good()) {
// put an error message here, or throw an exception. Up to you.
}
}
Once you're in couteverything(), presumably you want to loop over the entire file. You need a loop for that, not an if statement. Something like this:
while (getline(db_file, line)) {
cout << line;
cout << "ok";
}
Even if you did not want to loop here (in which case coutnextline() might be a better name for the method), you still want to test the result of getline() directly, rather than testing good() and is_open() before each read. You need to test whether getline() succeeds, otherwise your code will try to process one line beyond EOF or a read error.
if (getline(db_file, line)) {
cout << line;
cout << "ok";
}
If you do only want to output a line at a time, I'm not sure how the code that calls this would know when to stop. But, that's a different problem. (Hint: You could solve that by returning a bool from this line-at-a-time method.)