I came across the following observation while working with input and output file streams and I am confused. Can anyone tell me why this happens:
I saved a txt file on my desktop by the name hello which contains the following text:
Hello my name is xyz
Next, I ran the following code:
#include <iostream>
#include <fstream>
#include <string>
int main()
{
std::fstream strm;
strm.open("C:\\Users\\SWARAJ SONAVANE\\Desktop\\hello.txt");
if (strm.fail())
{
std::cout << "failed.... :(\n";
}
//std::string p;
//strm >> p;
//std::cout << p;
strm << "random text";
}
The content of the hello.txt file after running this code was:
random textme is xyz
Now i ran the following code on the original hello.txt file
#include <iostream>
#include <fstream>
#include <string>
int main()
{
std::fstream strm;
strm.open("C:\\Users\\SWARAJ SONAVANE\\Desktop\\hello.txt");
if (strm.fail())
{
std::cout << "failed.... :(\n";
}
std::string p;
strm >> p;
std::cout << p;
strm << "random text";
}
The console printed hello but the contents of the hello.txt file remained unaltered.
Can anybody explain, what difference did reading stream into the string make?
If you want to know how streams work in C++ then you need a reference work (and maybe a tutorial as well), obviously its much more complicated than can be explained here.
The reason for what you found is the rule that if you switch from reading to writing (or vice versa) you must execute a positioning or flushing operation before you make the switch. Try the following code instead
int main()
{
std::fstream strm;
strm.open("C:\\Users\\SWARAJ SONAVANE\\Desktop\\hello.txt");
if (strm.fail())
{
std::cout << "failed.... :(\n";
}
std::string p;
strm >> p;
std::cout << p;
strm.seekp(0); // position the stream at the beginning
strm << "random text";
}
Related
Given two files input.txt and delete.txt. Our Task is to perform file extraction(Input-Delete) and save the output in the file say output.txt
Example image
Show some research effort when you post a question here.
#include <iostream>
#include <unordered_set>
#include <fstream>
int main()
{
std::unordered_set<std::string> mySet;
std::string word;
std::ifstream file1("myFile1.txt");
if(file1.is_open())
{
while(file1 >> word)
mySet.emplace(word);
file1.close();
}
std::ifstream file2("myFile2.txt");
if(file2.is_open())
{
while(file2 >> word)
{
auto look = mySet.find(word);
if(look != mySet.cend())
mySet.erase(look);
}
file2.close();
}
std::ofstream outputFile("Out.txt");
if(outputFile.is_open())
{
for(const auto &it: mySet)
outputFile << it << '\n';
outputFile.close();
}
return 0;
}
EDIT:
I don't know what do you mean by not working. just debug your code, before you write the final set of strings to the output file, that's what I can say.
Just use the following and see what do you get:
for(const auto &it: mySet)
std::cout << it << '\n';
For instance I am getting the requeried output what do you mentioned in the picture.
Here is my console output:
I have a c++ program like this:
#include<iostream>
using namespace std;
class A
{
public:
void display();
};
void A::display() {
cout<<"This is from first program";
}
int main()
{
A a1;
a1.display();
return 0;
}
I want to save a1 into a file and call the display function by using this object from another c++ program. Is it possible? Is it possible to have main() function in both c++ programs? I am very new in C++. Please help me.
Given your comments, I believe that you're looking for std::ofstream in your first program and std::ifstream in your second program. If program A is your first program with a very large code base and program B is your second program which will want to display the data from program A, then program A would use std::ofstream and program B would use std::ifstream.
cppreference - ofstream
cppreference - ifstream
If you follow the links, you'll find the description of what they do and at the bottom of the page, there's a code example. Don't start with program A that takes 7-8 hours to compute. You'll have to make sure that the output is correct before you can even use the data for input and any mistake on the way means that you'll have to restart. If you want to test and manually verify your data you can skip the second parameter as such, std::ofstream ostrm(filename) but then you need to rework how you operate the stream. Depending on your data, this will be the critical part of the operation.
// Code example from cppreference - ofstream
#include <iostream>
#include <fstream>
#include <string>
int main() {
std::string filename = "Test.b";
{
// This will create a file, Test.b, and open an output stream to it.
std::ofstream ostrm(filename, std::ios::binary);
// Depending on your data, this is where you'll modify the code
double d = 3.14;
ostrm.write(reinterpret_cast<char*>(&d), sizeof d); // binary output
ostrm << 123 << "abc" << '\n'; // text output
}
// Input stream which will read back the data written to Test.b
std::ifstream istrm(filename, std::ios::binary);
double d;
istrm.read(reinterpret_cast<char*>(&d), sizeof d);
int n;
std::string s;
istrm >> n >> s;
std::cout << " read back: " << d << " " << n << " " << s << '\n';
}
With your data correctly outputted to a file you'll be able to read from it by creating the std::ifstream. Make sure to verify that the stream is open:
std::ifstream istrm(filename, std::ios::binary);
if(istrm.is_open())
{
//Process data
}
This will be your File.h
#ifndef FILE_H
#define FILE_H
class A
{
public:
void display();
};
#endif
This will be your File.cpp
#include <iostream>
#include "File.h"
void A::display() {
std::cout<<"This is from first program";
}
This will be you main.cpp
#include <iostream>
#include "File.h"
int main()
{
A a1;
a1.display();
return 0;
}
You compile this with g++ File.cpp main.cpp
So I'm doing the Euler Projects and I'm storing all my Solutions in one Program. I have just started on C++, so I don't know if this is a good way to do it. Anyway, each .cpp file contains one Problem. So basically my structure is like this:
"Executer.cpp"
include <iostream>
include "other.h"
int main() {
Problem1();
Problem2();
// etc.
system("pause")
return 0;
}
"Other.h"
void Problem1();
void Problem2();
// etc.
"Problem_X.cpp" (X denotes the number of the task). I have a lot of these files.
/* PROBLEM X
*/
#include <iostream>
#include <fstream>
#include <time.h>
void ProblemX() {
time_t t1, t2;
t1 = clock();
// Code goes here
t2 = clock();
float diff((float)t2 - (float)t1);
float seconds = diff / CLOCKS_PER_SEC;
// Results
std::ofstream myFile("result.txt");
//myFile << sum;
myFile.close();
std::cout << "-------------------- Problem X -------------------" << std::endl;
std::cout << "I ran for: " << seconds << " seconds" << std::endl << std::endl;
}
Now, the Projects consist of almost 600 Problems, which means I have to create 600 files and copy the template to each of those documents. So I thought I could just make a program for doing it.
Basically, I put "Problem_X.cpp" into a text file called "standard.txt". I then wrote the following program, which i run from my int main by including the function declaration in "other.h" and calling the function from "Executer.cpp". It runs fine when copying text from one text-file to another text-file. But now (I assume since I'm trying to copy into a .cpp file) nothing happens:
#include <fstream>
#include <iostream>
#include <sstream>
void CreateNewFile(int number) // denotes the number of the problem you wish to create
{
std::string strNumber = static_cast<std::ostringstream*>(&(std::ostringstream() << Number))->str();
std::string str1 = "Problem_";
std::string str2 = ".cpp";
std::string strr;
strr.append(str1); strr.append(strNumber); strr.append(str2);
std::ofstream out(strr); //this creates it.
std::ifstream in("standard.txt");
if (!out.is_open())
{
std::cout << "ERROR: Can not open document2.txt" << std::endl;
return;
}
std::string str;
while (std::getline(in, str)) {
out << str << std::endl;
}
in.close();
out.close();
}
Does anyone have experience doing something like this? I can't find any posts on google and I am out of ideas about where to look.
The program actually runs as is is intended. It creates the new "Problem_X.cpp" files just right. They are just not imported in the VS source folder. If anyone has a quick solution for this, they are welcome to leave it in a comment here.
For some reason, I can't write anything to a .PGM file. The following code compiles without errors but nothing is written to the .PGM file it creates. I'm fairly new to C++ and pretty unfamiliar with working with strings in this syntax.
#include <iostream>
#include <iomanip>
#include <fstream>
#include <cstring>
#include <sstream>
int main(){
// Initialize variables.
const int ncols = 30;
const int nrows = 20;
const int maxval = 255;
std::string filename;
// Prompt user for filename.
std::cout << "What would you like to name the file of the PGM image? Please include .PGM at the end of your name." << std::endl;
// Uses getline() function to retrieve input from user into a string.
std::getline(std::cin, filename);
// Creates output stream object to use with managing the file.
std::ofstream fileOut(filename.c_str(),std::ios_base::out
|std::ios_base::binary
|std::ios_base::trunc
);
fileOut.open(filename.c_str());
fileOut << "P2" << " " << ncols << " " << nrows << " " << maxval << "\n";
fileOut.close();
}
I know there is another SO question similar to this one, but I used that answer to get here. I can't even get it to write the header part and that's not even the point of the assignment. Can anyone help?
I want to create some text file in C++. For example: I will run a loop from 1 to 5 and create the following files:
1.txt
2.txt
3.txt
4.txt
5.txt
is it possible? I have made a sample code:
#include<iostream>
#include<cstdio>
#include<cstdlib>
using namespace std;
main()
{
FILE *fp;
int i;
for(i=1;i<=5;i++)
{
//fp=fopen("%d.txt","r",i); //what will go here??
}
}
I am confused about what I will write inside the loop. how can I create those files?
char i;
char fileName[] = "0.txt";
for(i='1';i<='5';i++)
{
fileName[0]=i;
fp=fopen(fileName,"r"); //what will go here??
//...
}
You can use sprintf if this is too simple for your case;
Since you tag c++, I think fstream string is the thing to use.
A simple c++ example
#include <fstream>
#include <string>
using namespace std;
int main(){
string base(".txt");
for(int i=1;i<=5;++i){
ofstream(to_string(i)+base);// to_string() need c++11
}
}
If you still don't have to_string (you don't have c++11 or your compiler just don't have this) you can use this simple version for now. (better put this in your own namespace)
#include <string>
#include <sstream>
std::string to_string(int i){
std::stringstream s;
s << i;
return s.str();
}
You can use a std::stringstream to compose the file name before passing it to the std::ofstream constructor as a std::string.
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <iomanip>
int main()
{
std::cout << "How many files do you want to create? ";
int n;
std::cin >> n;
std::cout << "How many digits do you want to display? ";
int n_digits;
std::cin >> n_digits; // i.e. zeroes == 3 -> 001.txt
std::cout << "Enter a common prefix for all the files: ";
std::string prefix;
std::cin.ignore();
std::getline(std::cin, prefix); // i.e. prefix == "file" -> file001.txt
std::string ext(".txt");
for ( int i = 1; i <= n; ++i )
{ // use a stringstream to create a file names like: prefix001.txt
std::stringstream ss;
ss << prefix << std::setfill('0') << std::setw(n_digits) << i << ext;
// open the file. If not c++11 use ss.str().c_str() instead
std::ofstream file( ss.str() );
if ( !file )
{
std::cerr << "Error: failed to create file " << ss.str() << '\n';
break;
}
// write something to the newly created file
file << "This is file: " << ss.str() << "\n\nHello!\n";
if ( !file )
{
std::cerr << "Error: failed to write to file " << ss.str() << '\n';
break;
}
}
}
#include <iostream>
#include <fstream>
int main(void)
{
std::ofstream out; // you must call out.close() inside loop to be able to open another file for writting otherwise you'll get only the first one "a.txt"
std::string sFileName;
for(char c('a'); c < 'f'; c++)
{
sFileName = c;
sFileName += ".txt";
out.open(sFileName.c_str(), std::ios::out);
// std::ofstream out(sFileName.c_str(), std::ios::out); // here you are not obliged to call out.close() because the first out is not the very second and so on...
out.close(); // very important if you use the same ofstream to open another file
}
std::cout << std::endl;
return 0;
}
*** to be able to use one ostream object in opening many files you must close the precedent file to be able to open the next otherwise it fails trying creating the next one.