Set string to file contents c++ - c++

I was wanting to know if there was a simple way to set a std::string equal to the contents of a file in C++. So far, I was thinking something like this: (although I haven't tested it, so I don't know if it will work)
#include <fstream>
#include <string>
int main(int argc, char *argv[]){
fstream in("file.txt");
string str;
str = in;
return 0;
}
Is this a way to accomplish this? If not, is there a simple way to do so? Thanks!

Here is one possible solution using vector<string>, each element is a line.
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
// vector that will store all the file lines
vector<string> textLines;
// string holding one line
string line;
// attach input stream to file
ifstream inputFile("data.txt");
// test stream status
if(!inputFile)
{
std::cerr << "Can't open input file!\n";
}
// read the text line by line
while(getline(inputFile, line))
{
// store each line as vector element
textLines.push_back(line);
}
// optional (stream object destroyed at end of function scope)
inputFile.close();
return 0;
}

There is a standard way:
std::ifstream file("myfilename.txt");
std::stringstream buffer;
buffer << file.rdbuf();
std::string content( buffer.str() );
References
http://en.cppreference.com/w/cpp/io/basic_ostream/operator_ltlt specially item (8)

try this one
#include <fstream>
#include <cstdlib>
std::string readText(const char* fileName)
{
std::ifstream file(fileName);
if (!file.good())
{
std::cout << "file fail to load..." << fileName;
exit(1);
}
return std::string(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>());
}

Related

c++ how to read and write from a specific line in a textfile?

hi I am trying to read a specific line from a text file update that and put it back to the same line without affecting the other lines in c++
here I am trying to execute the code and values get added when I re-execute it
#include <iostream>
#include <stream>
#include <stdio.h>
#include <string>
#include <stream>
using namespace std;
void stringGen(char num){
ifstream ifile;
ifile.open("example1.txt");
if(ifile) {
int LINE = 5;
string line;
ifstream myfile1 ("example1.txt");
for (int i = 1; i <= LINE; i++)
getline(myfile1, line);
cout << line<<endl;
stringstream geek(line);
int num=0;
geek>>num;
if(num<61004){
num=num+1;
ofstream MyFile("example1.txt");//
MyFile.close();
}
else{
num=61001;
ofstream MyFile("example1.txt");//
MyFile << num;
MyFile.close();
}
}
else{
int num=61001;
cout<<num<<endl;
ofstream MyFile("example1.txt");//
MyFile << num+1;
MyFile.close();
}
}
int main (){
char num;
stringGen(num);
return 0;
}
At first, you need to understand, how files, with lines are stored. Simplified, it is a sequence of bytes, one byte after the other. There maybe some special characters in this byte sequence, which people can interprete as the end of a line, e.g. '\n'. But also other characters or even more than one character is possible:
If you look at the following text.
Hello1
World1
Hello2
World2
it maybe stored in a file like this:
Hello1\nWorld1\nHello2\nWorld2\n
And just because we interprete a '\n' as the end of the line, we can "see" lines in there.
So, if you want to modify a line, then you would need to find the start position of the thing that we interprete as a line in the file, and then modify some bytes.
That can of course only be done, if the length of the "line" will not change. Then you could use "seek" functions and overwrite the needed bytes.
In reality, nobody would do that. Normally, you would read "lines" of the file into some kind of memory buffer, then do the modification there and then write back all lines.
For example, you would define a std::vector and then read all lines, by using std::getline and push_back the lines in the std::vector.
The modifications will be done in the std::vector, and the all data will be written back to the file, overwriting all "old" data.
There are more answers to this question. If you have any more specific question, I will answer again
Some simple example code
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
int main() {
// Here we will store all lines of the text file
std::vector<std::string> lines{};
// Open the text file for reading and check, if it could be opened
if (std::ifstream textfileStream{ "test.txt" }; textfileStream) {
// Read all lines into our vector
std::string oneLine{};
while (std::getline(textfileStream, oneLine)) {
// Add the just read line to our vector
lines.push_back(oneLine);
}
// For test purposes, modify the first line
if (not lines.empty()) lines[0] = "MODIFIED";
}
else std::cerr << "\nError: Could not open input text file\n";
// Write back data
// Open the text file for writing and check, if it could be opened
if (std::ofstream textfileStream{ "r:\\test.txt" }; textfileStream) {
// Iterate over all lines and wriite to file
for (const std::string& oneLine : lines)
textfileStream << oneLine << '\n';
}
else std::cerr << "\nError: Could not open output text file\n";
return 0;
}
#include <iostream>
#include <fstream>
#include <stdio.h>
#include <string>
#include <sstream>
using namespace std;
void stringGen(char num){
int count=0;
int a;
string line,check,linex;
string msg="Message_Handler:";
fstream ifile;
ifile.open("sample.txt",ios::in|ios::out);
if(ifile){
while(getline (ifile,line)) {
if (line.find("Message_Handler:") == 0){
check=line.substr(16,5);
count++;
a=ifile.tellp();
}
}
ifile.close();
if(count==0){
int num=61001;
cout<<num<<endl;
num=num+1;
ofstream examplefile ("sample.txt",ios::app);
examplefile<<"Message_Handler:"<<num;
examplefile.close();
}
if(count==1){
cout<<check<<endl;
stringstream geek(check);
int num=0;
geek>>num;
if(num<61004){
num=num+1;
stringstream ss;
ss << num;
string nums = ss.str();
fstream MyFile("sample.txt",ios::in|ios::out);
MyFile.seekp(a-5);
MyFile<<nums;
}
else{
int num=61001;
stringstream ss;
ss << num;
string nums = ss.str();
fstream MyFile("sample.txt",ios::in|ios::out);
MyFile.seekp(a-5);
MyFile<<nums;
}
}
}
else{
int num=61001;
cout<<num<<endl;
ofstream MyFile("sample.txt",ios::app);
MyFile <<"Message_Handler:"<< num+1;
MyFile.close();
}
}
int main (){
char num;
stringGen(num);
return 0;
}

How to use instream and ofstream to read and output a text file?

#include <iostream>
#include <cstring>
#include <fstream>
using namespace std;
ifstream in ("input.txt");
ofstream out ("output.txt");
int main(){
char collection [30];
while ( in.good() ){
in >> collection;
}
cout << collection[0] <<endl;
in.close();
out.close();
return 0;
}
I'm trying to read a text file in C++ programming.But it certainly is not working since it doesn't print anything. It's just a single line containing some operands. Can someone help me out?
Put those definitions of in and out inside main. Don't create global variables unless you absolutely have to.
The code loops through the input, and overwrites the contents of collection each time through the loop. When it reaches the end of the input, it writes out the first character in collection. It should either display what it read each time through the loop, or add each string that it reads into a container. If it's the former, the code would look like this:
#include <fstream>
#include <iostream>
int main() {
std::ifstream in("input.txt");
std::string input;
while (in >> input)
std::cout << input << '\n';
return 0;
}
Note that the original code didn't use out, so I left it out here. Also, when in is an auto object (i.e., defined inside main), when main returns it gets destroyed. One of the things that the destructor does is close the file, so there is no need to call in.close();.
If you want to put the input into some kind of collection, that's a straightforward change:
#include <fstream>
#include <iostream>
#include <vector>
int main() {
std::ifstream in("input.txt");
std::string input;
std::vector<std::string> collection;
while (in >> input) {
collection.push_back(input);
std::cout << input << '\n';
}
std::cout << "Contents of collection:\n";
for (auto& x : collection)
std::cout << x << '\n';
return 0;
}
If you want to write the text to an output file, just do it:
#include <fstream>
int main() {
std::ifstream in("input.txt");
std::ofstream out("output.txt");
std::string input;
while (in >> input)
out << input << '\n';
return 0;
}
That will write each word from the input onto a separate line in the output file. If you just want to copy the file unchanged, that's even easier:
#include <fstream>
int main() {
std::ifstream in("input.txt");
std::ofstream out("output.txt");
out << in.rdbuf();
return 0;
}

ifstream passed by reference to constructor can't be read

I don't understand why my ifstream can not be read in my class. In the main.cpp reading from the stream works fine, but when I pass the ifstream by reference to the c'tor I am not able to read from it. The program compiles fine but the 'inputfile' seems to be empty. In the console, I just see the content of my .txt once which comes from the main.cpp.
Am I doing something wrong with passing the ifstream?
main.cpp:
#include <iostream>
#include <fstream>
#include <string>
#include "RAM.h"
int main(int argc, char** argv)
{
std::ifstream input;
input.open("\\path\\orders.txt");
std::string line;
while (std::getline(input, line))
{
std::cout << line << std::endl;
}
RAM machine(input);
}
RAM.h:
#pragma once
#include <fstream>
class RAM
{
private:
std::ifstream& inputfile;
public:
RAM(std::ifstream&);
~RAM();
};
RAM.cpp:
#include "RAM.h"
#include <iostream>
#include <fstream>
#include <string>
RAM::RAM(std::ifstream &in) : inputfile(in){
std::string line;
while (std::getline(inputfile, line))
{
std::cout << line << std::endl;
}
}
RAM::~RAM() {
}
orders.txt:
ADD 5
SUB 7
HLT 99
The input file appears to be empty since you have already read all the data in main(). In other words, you're at the end of the file:
// File just opened, at position 0.
std::string line;
while (std::getline(input, line))
{
std::cout << line << std::endl;
}
// File fully read, at end of file.
RAM machine(input);
If you want to re-read it, you'll need to seek back to the start before attempting to re-read in the constructor, something like:
inputfile.seekg(0);

How to read a txt file and put it on a array with c++?

I have this .txt file that has a lot of words ( one each line ).
I tried
ifstream myReadFile;
myReadFile.open("restrict_words.txt");
char output[100];
if (myReadFile.is_open()) {
while (!myReadFile.eof()) {
printf("mamao");
myReadFile >> output;
cout<<output;
}
}
But i dont know how to make it work like... where should i pass it path and stuff
I would like to do
while(reading){
stringArray.add(file.line);
}
How can i do that?
First, this: (!myReadFile.eof()) is wrong. See the link for why. Second. If all you want is to load a file of strings into an array, this will do it:
#include <iostream>
#include <fstream>
#include <iterator>
#include <string>
#include <vector>
int main()
{
std::ifstream inp("restrict_words.txt");
std::istream_iterator<std::string> inp_it(inp), inp_eof;
std::vector<std::string> words(inp_it, inp_eof);
// words now has ever whitespace separated string
// from the input file as a vector entry
for (auto s : words)
std::cout << s << '\n';
}
Suggested reading:
std::vector<>
std::string
std::istream_iterator<>
C++11 Range-based for loop
Do you mean this?
//untested
#include <vector>
#include <fstream>
#include <string>
#include <iostream> //edited
int main()
{
std::ifstream ist("restrict_words.txt");
std::string word;
std::vector<std::string> readWords;
while(ist >> word)
readWords.push_back(word);
//test
for(unsigned i = 0; i != readWords.size(); ++i)
std::cout << readWords.at(i) << '\n'; // or readWords[i] (not range checked)
}
EDIT:
For each individual line you would do:
std::string line;
std::vector<std::string> readLines;
while(std::getline(ist, line))
{
readLines.push_back(line);
}

C++ Putting text from a text file into an array as individual characters

I want to put some text from a text file into an array, but have the text in the array as individual characters.
How would I do that?
Currently I have
#include <iostream>
#include <fstream>
#include <string>
#include <cmath>
#include <vector>
#include <sstream>
using namespace std;
int main()
{
string line;
ifstream myfile ("maze.txt");
if (myfile.is_open())
{
while ( myfile.good() )
{
getline (myfile,line);
// --------------------------------------
string s(line);
istringstream iss(s);
do
{
string sub;
iss >> sub;
cout << "Substring: " << sub << endl;
} while (iss);
// ---------------------------------------------
}
myfile.close();
}
else cout << "Unable to open file";
system ("pause");
return 0;
}
I'm guessing getline gets one line at a time. Now how would I split that line into individual characters, and then put those characters in an array?
I am taking a C++ course for the first time so I'm new, be nice :p
std::ifstream file("hello.txt");
if (file) {
std::vector<char> vec(std::istreambuf_iterator<char>(file),
(std::istreambuf_iterator<char>()));
} else {
// ...
}
Very elegant compared to the manual approach using a loop and push_back.
#include <vector>
#include <fstream>
int main() {
std::vector< char > myvector;
std::ifstream myfile("maze.txt");
char c;
while(myfile.get(c)) {
myvector.push_back(c);
}
}