flush out buffer into file - c++

int main()
{
string line;
char buff[10];
for(int i=0; i<10;i++)
{
cin.get(buff[i]);
cout.put(buff[i]);
if(i==10)
{
ofstream file;
file.open("TEXT",ios::out);
for (i=0 ; i<10 ;i++)
file << buff[i] << endl;
file.close();
}
}
}
this code is not flushing the data from array to file and even file is also not created...

No, because inside your loop, i<10, so your conditional is never executed. Put the flushing code after the loop.

Related

File isn't being read? (C++)

I am attempting to read numbers from a text file into a program, but for some reason, the program isn't reading the file. Here is my code:
#include <iostream>
#include <stream>
using namespace std;
int main()
{
ifstream infile;
infile.open ("adventDay1.txt");
if (!infile) { //Check if file is opening
cerr << "Error!"<< endl;
return 0;
}
int dataSize = 0;
infile >> dataSize;
int* arr;
arr = new int[dataSize]; //dynamically allocated array
int measureCount = 0; //Keep track of input from file
for (int i = 0; i < dataSize; i++) {
// infile >> dataSize;
arr[i] = dataSize;
measureCount += 1;
}
cout << measureCount << endl;
delete[] arr; //Delete dynamically allocated memory
return 0;
}
Each time I run it, it just displays the "Error!" message I added. There are 2,000 numbers in the text file, so that should be the expected output based on what I have here. I can't pinpoint the mistake.
Include fstream and ensure that you are opening the file in read mode. Perhaps also define it as ifstream infile("adventDay1.txt")

c++ nested while loop runs only once

Please can you advise, why the inner loop runs only once?
I'd like to add suffix to each line of input file and then store the result in output file.
thanks
For example:
Input file contains:
AA
AB
AC
Suffix file contains:
_1
_2
Output file should contain:
AA_1
AB_1
AC_1
AA_2
AB_2
AC_2
My result is :
AA_1
AB_1
AC_1
Code:
int main()
{
string line_in{};
string line_suf{};
string line_out{};
ifstream inFile{};
ofstream outFile{"outfile.txt"};
ifstream suffix{};
inFile.open("combined_test.txt");
suffix.open("suffixes.txt");
if (!inFile.is_open() && !suffix.is_open()) {
perror("Error open");
exit(EXIT_FAILURE);
}
while (getline(suffix, line_suf)) {
while (getline(inFile, line_in))
{
line_out = line_in + line_suf;
outFile << line_out << endl;
}
inFile.close();
outFile.close();
}
}
IMHO, a better method is to read the files into vectors, then iterate through the vectors:
std::ifstream word_base_file("combined_test.txt");
std::ifstream suffix_file("suffixes.txt");
//...
std::vector<string> words;
std::vector<string> suffixes;
std::string text;
while (std::getline(word_base_file, text))
{
words.push_back(text);
}
while (std::getline(suffix_file, text))
{
suffixes.push_back(text);
}
//...
const unsigned int quantity_words(words.size());
const unsigned int quantity_suffixes(suffixes.size());
for (unsigned int i = 0u; i < quantity_words; ++i)
{
for (unsigned int j = 0; j < quantity_suffixes; ++j)
{
std::cout << words[i] << suffix[j] << "\n";
}
}
Edit 1: no vectors
If you haven't learned about vectors or like to thrash your storage device you could try this:
std::string word_base;
while (std::getline(inFile, word_base))
{
std::string suffix_text;
while (std::getline(suffixes, suffix_text))
{
std::cout << word_base << suffix_text << "\n";
}
suffixes.clear(); // Clear the EOF condition
suffixes.seekg(0); // Seek to the start of the file (rewind).
}
Remember, after the inner while loop, the suffixes file is at the end; no more reads can occur. Thus the file needs to be positioned at the start before reading. Also, the EOF state needs to be cleared before reading.

How to use fstream, to write different values in a .txt file

The problem I am facing is the following:
if we define something like
ofstream myFile;
myFile.open("Directory//debug.txt");
for (int i = 0; i < 10; i++)
{
myFile << i << endl;
myFile.close();
}
the output in the debug file will be 9.
I want to make it so that it outputs all the numbers from 0 to 9. Aside from closing the file after the for statement is it possible to define an ofstream that would do that?
No. You have two options:
Close the file outside the loop:
myFile.open("Directory//debug.txt");
for (int i = 0; i < 10; i++)
{
myFile << i << endl;
}
myFile.close();
or open the file in append mode and close inside the loop:
for (int i = 0; i < 10; i++)
{
myFile.open("Directory//debug.txt", ios_base::app);
myFile << i << endl;
myFile.close();
}
myFile.close();
should be put after the for-loop. Also introduce some error checking to see if the open was indeed a success.
I am calling a function foo repeatedly in a function goo I create the
file in foo and I want to output a new value each time foo is called
in goo.
In order to achieve your objective you could use a static variable inside foo
void foo()
{
static int count=0;
ofstream myfile;
myfile.open("Directory//debug.txt",std::fstream::app)
if (myfile.is_open()) // Checking is file is successfully opened.
{
count++;
myfile<<count<<"\n";
}
myfile.close; // Close the file
}

How to read a table from .txt file to C++

I want to read a matrix from a file and use it in my program. but when I output the results, it shows that it is not reading correctly.
Here is the code:
#define I 5
#define J 5
#define P 2
int i,j,k; //for loops
int main ()
{
ifstream inFile;
ofstream outFile;
double C[I][J];
inFile.open("C.txt", ios::in);
if (! inFile) {
cerr << "unable to open file C.txt for reading" << endl;
return 1;
}
for(i=0; i<I; i++)
for(j=0; j<J; j++)
inFile >> C[i][j];
outFile.open("results.txt");
outFile<< "C" <<endl;
for(i=0;i<I;i++)
{
for(j=0;j<J;j++)
outFile<< C[i][j];
outFile<< endl;
}
inFile.close();
outFile.close();
return 0;
}
C is a matrix of integer values 2 3 5... but what I get is
316-9.25596e+061-9.25596e+061-9.25596e+061-9.25596e+061
-9.25596e+061-9.25596e+061-9.25596e+061-9.25596e+061-9.25596e+061 -9.25596e+061-9.25596e+061-9.25596e+061-9.25596e+061-9.25596e+061 -9.25596e+061-9.25596e+061-9.25596e+061-9.25596e+061-9.25596e+061 -9.25596e+061-9.25596e+061-9.25596e+061-9.25596e+061-9.25596e+061
You should output a whitespace after each number, otherwise they will be all glued together.
outFile<< C[i][j] << " ";
You also should check your input for validity. Not showing it here (you already know how to check if (! inFile)).
I suspect that you are having problems with new lines, below modification will ignore new line character after reading each line:
for(i=0; i<I; i++) {
for(j=0; j<J; j++)
inFile >> C[i][j];
inFile.ignore(); /// <<<--------
}
It seems you are writing uninitialized variables to your output file, leading to undefined behavior.
I suspect your C.txt file does not contain the 5x5 matrix your program is looking for.
You should add a simple error check, e.g.:
for(i=0; i<I; i++)
for(j=0; j<J; j++)
if (!(inFile >> C[i][j])) { /* something's wrong here */ }

Copying a file multiple times using loop; C/C++

I wanted to copy a file multiple times using different names.
The program is this:
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include <sstream>
#include<cstring>
using namespace std;
main()
{
string text;
int i;
char ch;
ostringstream oss;
FILE *fp1,*fp2;
if((fp1=fopen("One Dollar.jpg", "rb"))==NULL)
{
cout<<"Error";
exit(-1);
}
for(i=1; i<=5; i++)
{
oss << "C:\\5241 Dollar\\One Dollar " << i << ".jpg";
text = oss.str();
if((fp2=fopen(text.c_str(), "wb"))==NULL)
{
cout<<"Error "<<i;
exit(-1);
}
while(!feof(fp1))
{
fread(&ch, 1, 1, fp1);
fwrite(&ch, 1, 1, fp2);
}
fclose(fp2);
/* for(int j=0;j<30000;j++)
for(int k=0;k<30000;k++)
if(k==3000)
cout<<k; */
}
fclose(fp1);
}
In this there are two file streams one of which is source and the other is destination.. I loaded the actual file in binary read mode and the destination as binary write mode. I used a for loop to do the work. But as soon as the loop iterates 2nd time, the file opening of fp2 fails. I'm getting the output: Error 2.
How can I make the code work?
You should open and close the first file in each iteration of the loop.
....
for(i=1; i<=5; i++)
{
if((fp1=fopen("One Dollar.jpg", "rb"))==NULL)
{
cout<<"Error";
exit(-1);
}
....
The reason is because at the end of the first iteration, the first file pointer is at the end of the file, so it won't see any data at the second iteration. You have to close and reopen the file (OR you can use seek to jump to the front of the file, but this is the simpler change since its a copy-and-paste)
EDIT: to the new question:
you need to reset the stringstream. In the second iteration you are trying to open
C:\\5241 Dollar\\One Dollar 1.jpgC:\\5241 Dollar\\One Dollar 2.jpg
which is invalid.
One solution is to bring the ostringstream declaration into the loop:
....
for(i=1; i<=5; i++)
{
if((fp1=fopen("One Dollar.jpg", "rb"))==NULL)
{
cout<<"Error";
exit(-1);
}
ostringstream oss;
oss << "C:\\5241 Dollar\\One Dollar " << i << ".jpg";
int main()
{
string text;
int i;
char ch;
ostringstream oss;
FILE *fp1,*fp2;
if((fp1=fopen("/home/maru/fact.cpp", "rb"))==NULL)
{
cout<<"Error";
exit(-1);
}
for(i=1; i<=5; i++)
{
oss << "/home/maru/fact" << i << ".cpp";
text = oss.str();
rewind(fp1);
cout<<text<<"\n";
if((fp2=fopen(text.c_str(), "wb"))==NULL)
{
cout<<"Error "<<i;
exit(-1);
}
while(!feof(fp1))
{
fread(&ch, 1, 1, fp1);
fwrite(&ch, 1, 1, fp2);
}
fclose(fp2);
oss.str("");
}
fclose(fp1);
return 0;
}