how to read data in c++ from a file stored in any other structure e-g: .text file [closed] - c++

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.

Related

Why does this line not output my text file? [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 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.

How to save .txt file in C++? [duplicate]

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.

I can't read a single line using getline() [closed]

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.)

Skip last K lines while traversing a file [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
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
Closed 9 years ago.
Improve this question
A user had posted a similar question earlier this day which was very soon closed due to its vagueness. Thus re-posting the question in detail with a solution as I didn't find a specific article dealing with it on the internet.
The requirement is to read and print all lines of a file except the last K.
Suppose a file contains text as:
Hello there!
My name is
Mr. XYZ
I like playing football
And if K is 2, then it should print all the lines except the last 2. i.e.:
Hello there!
My name is
Why not simply put lines into a std::deque and dump one element when its size is greater k ?
#include<iostream>
#include<fstream>
#include<deque>
int main()
{
std::fstream fs;
fs.open("output.txt",std::ios::in);
std::deque<std::string> deq;
std::string str;
int k=2;
while(std::getline(fs,str))
{
deq.push_back(str);
if(deq.size() > k)
{
std::cout <<deq.front()<<std::endl;
deq.pop_front();
}
}
}
This can easily be solved by creating a window of size K and then traversing the file till the right end of the window reaches the end of the file. The basic steps being:
Traverse the first K lines of the file without printing it.
Open the same file using another stream object.
Now simultaneously traverse both the streams so that fisrt stream is always K lines ahead of the second stream.
Run a loop while the second first stream is valid. In the loop, read through the first stream as well and keep print the lines.
The code would be
#include<iostream>
#include<fstream>
#include<string>
int main()
{
fstream fs;
fs.open("abc.txt",ios::in);
string str;
int K = 2;
while(getline(fs,str) && K>1)
{
K--;
}
if(K==1)
{
fstream fsNew;
fsNew.open("abc.txt",ios::in);
while(getline(fs,str))
{
getline(fsNew,str);
cout<<str;
}
}
cin.ignore();
}

how would one go about finding specific words in a text file in c++ [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
how would i do this:
Got a text file called directorycontents.txt in this directorycontents.txt there is a bunch of text each one is a filename with a filename extension i want to be able to go like this if there is a filename extension of specific characters like .txt or .png then do fprintf(stderr,"whateva");
i have looked at istream and fstream and iostream but im not really shore how to use fstream to do this
thanks
Okay, I'll just point you to the right direction and I won't post any code, as you need to try it by yourself.
First of all, read about reading files in C++. You can google it and there are tons of information about this. You can try with "how to read text file in C++", for example.
Second, prefer using ofstream and/or ifstream - this is the C++ way to do it.
Then parse the file - you can read it word by word (using istream::operator>> ) , line by line (for example with getline ) into std::string (as you're talking about file names).
And then analize the input - analize the parsed file and search for specific words in it - for example, std::string has member functions like find - I think this will be enough for your problem :)
I hope that helps. Just note, that we don't write code here, we just help finding solutions for problems.
For something like this definitely take a look at std::fstreams. Based on your vague description of what you're trying to do, you can use this simple program as a starting point:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void doSomething();
int main(int argc, char *argv[])
{
if(argc < 2)
{
cout << "Usage: findsomething [filename]" << endl;
return 1;
}
ifstream infile(argv[1], ifstream::in);
if(!infile.is_open())
{
cout << "Couldn't open file " << argv[1] << endl;
return 1;
}
string line;
while(getline(infile, line))
{
if(line.find(".txt") != string::npos ||
line.find(".png") != string::npos ||
line.find(".bat") != string::npos)
{
doSomething();
}
}
}
Hopefully, that's enough code to get you started and it isn't too difficult for you to read.