I want to display all the text that is in the fille to the output,
I use by using the code below, the code I got up and results posts are just a little out
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
char str[10];
//Creates an instance of ofstream, and opens example.txt
ofstream a_file ( "example.txt" );
// Outputs to example.txt through a_file
a_file<<"This text will now be inside of example.txt";
// Close the file stream explicitly
a_file.close();
//Opens for reading the file
ifstream b_file ( "example.txt" );
//Reads one string from the file
b_file>> str;
//Should output 'this'
cout<< str <<"\n";
cin.get(); // wait for a keypress
// b_file is closed implicitly here
}
The above code simply displays the words "This" does not come out all into output.yang I want is all text in the file appear in the console ..
The overloaded operator>> for char* will only read up to the first whitespace char (it's also extremely risky, if it tries to read a word longer then the buf length you'll end up with undefined behavior).
The following should do what you want in the most simple manner, as long as your compiler supports the rvalue stream overloads (if not you'll have to create a local ostream variable and then use the stream operator):
#include <fstream>
#include <iostream>
int main()
{
std::ofstream("example.txt") << "This text will now be inside of example.txt";
std::cout << std::ifstream("example.txt").rdbuf() << '\n';
}
try something like this
#include <fstream>
#include <iostream>
using namespace std;
int main(){
string line;
ofstream a_file ( "example.txt" );
ifstream myfile ("filename.txt");
if (myfile.is_open()) {
while ( getline (myfile,line) ) {
a_file << line << '\n';
}
myfile.close();
a_file.close();
} else
cout << "Unable to open file";
}
Hope that helps
This is not the best way to read from a file. You probably need to use getline and read line by line. Note that you are using a buffer of fixed size, and you might cause an overflow. Do not do that.
This is an example that is similar to what you wish to achieve, not the best way to do things.
#include <fstream>
#include <iostream>
using namespace std;
int main() {
string str;
ofstream a_file("example.txt");
a_file << "This text will now be inside of example.txt";
a_file.close();
ifstream b_file("example.txt");
getline(b_file, str);
b_file.close();
cout << str << endl;
return 0;
}
This is a duplicate question of:
reading a line from ifstream into a string variable
As you know from text input/output with C++, cin only reads up to a newline or a space. If you want to read a whole line, use std::getline(b_file, str)
Related
Sometimes I see on the internet programs that read from a file like this:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
string line;
ifstream myfile ("example.txt");
if (myfile.is_open())
{
while ( getline (myfile,line) )
{
cout << line << '\n';
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
I want to know if while ( getline (myfile,line) ) means "as long as the text file has lines that haven't been read keep reading them" and if "while" can accept other conditions that I don't know about.
Also I want to know if there is a method to read a text file character by character not line by line.
In C++ you can read a file char by char as given example
char oneChar;
fstream fin("file", fstream::in);
while (fin >> noskipws >> oneChar)
{
cout << oneChar;
// or do desired operation with oneChar
}
You are correct about the while, it will keep reading until it finds EOF, or End-Of-File. While can accept anything that returns true or false, so any function that returns bool (or even numbers, etc) will work.
Here is what I got so far:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
int characterList = 0;
char* dynamo = new char[1000];
char* buffer = dynamo;
ifstream input("wordlist.txt");
if (input.is_open())
{
input >> dynamo[characterList];
while (input.eof())
{
characterList++;
input >> dynamo[characterList];
cout << dynamo[characterList];
}
}
else
{
cout << "File not opened" << endl;
}
return;
}
I'm a beginner so I do apologize if this looks like terrible coding practice. I created a text file with a quote from Bill Cosby that I'm trying to read one word at a time. The quote is "I don't know the key to success, but the key to failure is trying to please everybody." I'm trying to read one word at a time from a text document ignoring punctuation. I know there are a lot of questions similar to this, but they are using code that I have not learned so I'm sorry for having a repeating question. I have not learned getline (I used cin.getline) and #include <string>.
Edit: I forgot to mention, so I'm sorry for not doing so earlier, but I'm studying dynamic memory allocation which is why I'm using the new char[1000].
I'd suggest you to use std::string instead of manually allocating buffers on the heap with new[] and trying to read text manually from the file into those buffers (and don't forget to free the buffer with proper delete[] calls!).
C++ input stream classes like std::ifstream can simply read text into std::string instances thanks to a proper overload of operator<<.
The syntax is as simple as:
string word;
while (inFile >> word)
{
cout << word << endl;
}
Here's a complete compilable sample code for you to experiment and learn:
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main()
{
ifstream inFile("test.txt");
if (inFile.is_open())
{
string word;
while (inFile >> word)
{
cout << word << endl;
}
}
else
{
cout << "Can't open file." << endl;
}
}
This is the output I got on a test text file having the content specified in your question:
I
don't
know
the
key
to
success,
but
the
key
to
failure
is
trying
to
please
everybody.
NOTE
Of course, once you have your words read into a std::string instance, you can store them in a container like std::vector<std::string>, using its push_back() method.
I would do something like this:
#include <iostream>
#include <string>
#include <fstream>
int main() {
std::string array[6];
std::ifstream infile("Team.txt");
std::string line;
int i = 0;
while (std::getline(infile, line)) {
array[i++] = line;
}
return 0;
}
based on this answer.
Here, we assume we have to read 6 lines from the file "Team.txt". We use std:::getline() and we put inside a while so that we read all the file.
At every iteration, line holds the current line of the file read. Inside the body we store it in array[i].
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <process.h>
using namespace std;
int main(){
system("cls");
char mline[75];
int lc=0;
ofstream fout("out.txt",ios::out);
ifstream fin("data.txt",ios::in);
if(!fin){
cerr<<"Failed to open file !";
exit(1);
}
while(1){
fin.getline(mline,75,'.');
if(fin.eof()){break;}
lc++;
fout<<lc<<". "<<mline<<"\n";
}
fin.close();
fout.close();
cout<<"Output "<<lc<<" records"<<endl;
return 0;
}
The above code is supposed to read from the file "data.txt" the following text
"The default behaviour of ifstream type stream (upon opening files ) allows users
to read contents from the file. if the file mode is ios::in only then reading is
performed on a text file and if the file mode also includes ios::binary along with
ios::in then, reading is performed in binary mode. No transformation of characters
takes place in binary mode whereas specific transformations take place in text mode."
and create a file out.txt , in which the same text is stored using line numbers ( A line can have 75 characters or ends at '.' - whichever occurs earlier ).
Whenever I run the program, it just gets stuck at the console - which doesnt respond upon pressing any keys whatsoever.
Can someone tell me what's going on in here ?
If any one of the attempted reads in the file is longer than 74 characters, getline will set the failbit for fin, and you will never reach the end of the file. Change your code to the following:
for (; fin; ++lc) {
fin.getline(mline,75,'.');
if (!fin.eof() && !fin.bad())
fin.clear();
fout<<lc<<". "<<mline<<"\n";
}
This will break your loop if you reach the end of the file or if something catastrophic happens to the stream. You'll also need to think about handling the extra read that is performed if the file ends with a period.
Consider switching to std::string.
#include <iostream>
#include <fstream>
#include <string>
int main()
{
int lc = 0;
std::ofstream fout("out.txt");
std::ifstream fin("data.txt");
for (std::string line; getline(fin, line, '.'); )
fout << ++lc << ". " << line << "\n";
std::cout << "Output " << lc << " records\n";
}
I currently have this code, but I would like to be able to output to a .csv file, rather than just print to screen. Does anyone know how to do this?
#include <iostream>
#include <fstream>
#include <algorithm>
using namespace std;
string Weather_test;
int main()
{
ifstream Weather_test_input;
Weather_test_input.open("/Users/MyName/Desktop/Weather_test.csv");
getline(Weather_test_input, Weather_test, '?');
Weather_test.erase(remove_if(Weather_test.begin(), Weather_test.end(), ::isalpha), Weather_test.end());
cout << Weather_test;
return 0;
}
If the Weather_test string is formatted properly.
ofstream Weather_test_output("path_goes_here.csv", ios::app);
// this does the open for you, appending data to an existing file
Weather_test_output << Weather_test << std::endl;
Weather_test_output.close();
If it is not formatted properly then you need to separate it into "fields" and write them with commas between them. That's a separate question.
Writing a string to a CSV file is like writing a string to any file:
std::string text = "description"
output_file << description << ", " << 5 << "\n";
In your example, you can't write to an ifstream. You can write to ofstream and fstream but not ifstream.
So either open the file for reading and writing or close after reading and open as writing.
To write to csv is to create an ostream and open file named "*.csv". You can use operator<< on this object in the same way as you have used it previously to write to the standard output, std::cout:
std::ofstream f;
f.open( "file.csv", std::ios::out);
if ( !f) return -1;
f << Weather_test;
f.close();
Thanks people you here are all truly amazing!
I managed to get my final piece of code which (removes all letters of the alphabet from my .csv file). Here it is for posterity
#include <iostream>
#include <fstream>
#include <algorithm>
using namespace std;
string Weather_test;
int main()
{
ifstream Weather_test_input;
Weather_test_input.open("/Users/MyName/Desktop/Weather_test.csv");
getline(Weather_test_input, Weather_test, '?');
Weather_test.erase(remove_if(Weather_test.begin(), Weather_test.end(), ::isalpha), Weather_test.end());
ofstream Weather_test_output("/Users/MyName/Desktop/Weather_test_output.csv", ios::app);
Weather_test_output << Weather_test << std::endl;
Weather_test_output.close();
cout << Weather_test;
return 0;
}
Thanks again all!
I'm in a tutorial which introduces files (how to read from file and write to file)
First of all, this is not a homework, this is just general help I'm seeking.
I know how to read one word at a time, but I don't know how to read one line at a time, or how to read the whole text file.
What if my file contains 1000 words? It is not practical to read entire file word after word.
My text file named "Read" contains the following:
I love to play games
I love reading
I have 2 books
This is what I have accomplished so far:
#include <iostream>
#include <fstream>
using namespace std;
int main (){
ifstream inFile;
inFile.open("Read.txt");
inFile >>
Is there any possible way to read the whole file at once, instead of reading each line or each word separately?
You can use std::getline :
#include <fstream>
#include <string>
int main()
{
std::ifstream file("Read.txt");
std::string str;
while (std::getline(file, str))
{
// Process str
}
}
Also note that it's better you just construct the file stream with the file names in it's constructor rather than explicitly opening (same goes for closing, just let the destructor do the work).
Further documentation about std::string::getline() can be read at CPP Reference.
Probably the easiest way to read a whole text file is just to concatenate those retrieved lines.
std::ifstream file("Read.txt");
std::string str;
std::string file_contents;
while (std::getline(file, str))
{
file_contents += str;
file_contents.push_back('\n');
}
I know this is a really really old thread but I'd like to also point out another way which is actually really simple... This is some sample code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
ifstream file("filename.txt");
string content;
while(file >> content) {
cout << content << ' ';
}
return 0;
}
I think you could use istream .read() function. You can just loop with reasonable chunk size and read directly to memory buffer, then append it to some sort of arbitrary memory container (such as std::vector). I could write an example, but I doubt you want a complete solution; please let me know if you shall need any additional information.
Well, to do this one can also use the freopen function provided in C++ - http://www.cplusplus.com/reference/cstdio/freopen/ and read the file line by line as follows -:
#include<cstdio>
#include<iostream>
using namespace std;
int main(){
freopen("path to file", "rb", stdin);
string line;
while(getline(cin, line))
cout << line << endl;
return 0;
}
The above solutions are great, but there is a better solution to "read a file at once":
fstream f(filename);
stringstream iss;
iss << f.rdbuf();
string entireFile = iss.str();
you can also use this to read all the lines in the file one by one then print i
#include <iostream>
#include <fstream>
using namespace std;
bool check_file_is_empty ( ifstream& file){
return file.peek() == EOF ;
}
int main (){
string text[256];
int lineno ;
ifstream file("text.txt");
int num = 0;
while (!check_file_is_empty(file))
{
getline(file , text[num]);
num++;
}
for (int i = 0; i < num ; i++)
{
cout << "\nthis is the text in " << "line " << i+1 << " :: " << text[i] << endl ;
}
system("pause");
return 0;
}
hope this could help you :)
hello bro this is a way to read the string in the exact line using this code
hope this could help you !
#include <iostream>
#include <fstream>
using namespace std;
int main (){
string text[1];
int lineno ;
ifstream file("text.txt");
cout << "tell me which line of the file you want : " ;
cin >> lineno ;
for (int i = 0; i < lineno ; i++)
{
getline(file , text[0]);
}
cout << "\nthis is the text in which line you want befor :: " << text[0] << endl ;
system("pause");
return 0;
}
Good luck !
Another method that has not been mentioned yet is std::vector.
std::vector<std::string> line;
while(file >> mystr)
{
line.push_back(mystr);
}
Then you can simply iterate over the vector and modify/extract what you need/
The below snippet will help you to read files which consists of unicode characters
CString plainText="";
errno_t errCode = _tfopen_s(&fStream, FileLoc, _T("r, ccs=UNICODE"));
if (0 == errCode)
{
CStdioFile File(fStream);
CString Line;
while (File.ReadString(Line))
{
plainText += Line;
}
}
fflush(fStream);
fclose(fStream);
you should always close the file pointer after you read, otherwise it will leads to error