Edit
I've included #include <sstream> now. This helped. But still an issue displaying the correct information. I've stepped it out, and it has to deal with some sort of program error. I have the text file already made inside of the same folder path. I've tried setting it to a direct C:/ path such as
C:\Users\Matt\Documents\Visual Studio 2015\Projects\listofcolors.txt
I'm having problem opening my file and displaying data. I recently downloaded Microsoft Visual Basic C++ to write the program I need for Mastermind. My goal is to create numbers that represent 9 to the 5th and put them within a text file. (Essentially, 5 columns of 9 numbers, 9 I've written this so far.
#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;
int main() {
int a = 0;
int b = 0;
int c = 0;
int d = 0;
int e = 0;
std::string result;
std::stringstream sstm;
ofstream myfile;
myfile.open("listofcolors.txt");
if (myfile.is_open())
{
for (a = 0; a<9; a++) {
sstm << a << b << c << d << e;
result = sstm.str();
myfile << result << '\n';
for (b = 0; b<9; b++) {
sstm << a << b << c << d << e;
result = sstm.str();
myfile << result << '\n';
for (c = 0; c<9; c++) {
sstm << a << b << c << d << e;
result = sstm.str();
myfile << result << '\n';
for (d = 0; d<9; d++) {
sstm << a << b << c << d << e;
result = sstm.str();
myfile << result << '\n';
for (e = 0; e<9; e++) {
sstm << a << b << c << d << e;
result = sstm.str();
myfile << result << '\n';
}
}
}
}
myfile.close();
return 0;
}
}
else cout << "Unable to open file";
return 0;
}
For some reason, nothing is outputted. Any ideas??? Thank you!!
We can get clever by borrowing this arbitrary base conversion code that will output numbers in base 9 - see the cout version online here:
#include <iostream>
#include <iomanip>
#include <fstream>
#include <algorithm>
using namespace std;
/**
* C++ version 0.4 std::string style "itoa":
* Contributions from Stuart Lowe, Ray-Yuan Sheu,
* Rodrigo de Salvo Braz, Luc Gallant, John Maloney
* and Brian Hunt
*/
std::string itoa(int value, int base) {
std::string buf;
// check that the base if valid
if (base < 2 || base > 16) return buf;
enum { kMaxDigits = 35 };
buf.reserve( kMaxDigits ); // Pre-allocate enough space.
int quotient = value;
// Translating number to string with base:
do {
buf += "0123456789abcdef"[ std::abs( quotient % base ) ];
quotient /= base;
} while ( quotient );
// Append the negative sign
if ( value < 0) buf += '-';
std::reverse( buf.begin(), buf.end() );
return buf;
}
int main() {
ofstream myfile("listofcolors.text");
if (myfile.is_open())
{
for (int i = 0; i <= 9 * 9 * 9 * 9 * 9; i++)
{
// Formats the number to five places, filled with leading zeroes
myfile << setw(5) << setfill('0') << itoa(i, 9) << '\n';
}
myfile.close();
}
else
cout << "Unable to open file";
return 0;
}
Note that the file is created in the working directory; here is how to check and set where it is.
Also note that your code had the myfile.close() inside the first loop, so it would only have printed from 00000 to 08888.
Finally, since you are on Windows, use File Explorer to search for listofcolors.txt, just in case it is being created in an unexpected location.
On Windows, text files have a .txt file extension, not .text. Also, you are creating the file using a relative path, so it will be created in the process's current working directory, which may not be what you are expecting it to be. Always use absolute paths.
Your loop code is unnecessarily complex, it can be simplified to something more like this:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream myfile("C:\\some path\\listofcolors.txt", ios_base::trunc);
if (myfile.is_open())
{
for (int a = 0; a < 9; a++)
for (int b = 0; b < 9; b++)
for (int c = 0; c < 9; c++)
for (int d = 0; d < 9; d++)
for (int e = 0; e < 9; e++) {
if (!(myfile << a << b << c << d << e << '\n')) {
cout << "Unable to write to file";
return 0;
}
}
myfile.close();
cout << "File created";
}
else
cout << "Unable to create file";
return 0;
}
Related
#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;
int main() {
bool done = false;
cout << setprecision(20) << endl;
ifstream infile("in.txt");
ifstream outfile("out.txt");
while(!infile.eof()) {
int sign = 1;
double pi = 0;
long n;
infile >> n;
for(long i = 1; i < n; i += 2) {
pi += sign/(double)i;
sign = -sign;
}
pi *= 4;
cout << "value of pi for n = " << n << " is " << pi << endl;
}
return 0;
}
This reads from a file and prints to the console but I can't get the code to print to the outfile. I've tried doing
outfile<< "value of pi for n = " << n << " is " << pi << endl;
But that doesn't seem to work
It does not write to the file because you defined outfile as an std::ifstream
ifstream is for input files.
Define it as an ofstream and it should work.
Example:
ofstream outfile("out.txt");
Consider this program:
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
fstream file;
int line_count = 0;
int months;
string name_file;
std::cout << "Please input the file name for your report file: ";
std::cin >> name_file;
if (name_file != "load_report.txt")
{
std::cout << "Invalid report file!\n";
exit(1);
}
std::cout << "Please provide the number of months to consolidate: ";
std::cin >> months;
if (months <= 0)
{
std::cout << "You need to have at least one month in order to"
<< " consolidate your sales.\n";
exit(1);
}
std::cout << "\n";
file.open(name_file, ios::in);
if (file.is_open())
{
string line;
while (getline(file, line))
{
line_count++;
}
}
else
{
std::cout << "Could not open file!\n";
exit(1);
}
file.close();
file.open(name_file, ios::in);
vector<float> a(line_count);
int k = 0;
if (file.is_open())
{
for (auto & val : a)
{
file >> val;
}
}
else
{
std::cout << "Could not open file!\n";
exit(1);
}
file.close();
int loops = line_count / months;
for (int i = 0; i < loops; ++i)
{
float sum = 0;
std::cout << "Month ";
for (int j = 0; j < months; ++j)
{
std::cout << i * months + j + 1 << " ";
sum += a[i * months + j];
}
std::cout << "sales: $" << sum << "\n";
}
return 0;
}
Running make stylecheck returns the following:
16369 warnings generated.
/home/bl71/bl71/prob-02/prob-02-main.cpp:64:17: warning: calling a function that uses a default
argument is disallowed [fuchsia-default-arguments-calls]
vector<float> a(line_count);
^
/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_vector.h:507:29: note: default
parameter was declared here
vector(size_type __n, const allocator_type& __a = allocator_type())
^
Is there an argument that can be passed through to make this warning go away? This is a program I am trying to write that loads a monthly report from a report file and displays the consolidated sales for a given range of months. In my directory, a load_report.txt file was manually created and I use this program to read its contents of that file using fstream. make stylecheck checks for internal documentation guidelines.
I have to write out a list of prime numbers from 1-100, using a function we have previously wrote, to a file. The commented out part isn't anything related; it's just the previous code we used for the function. I don't know exactly what's going on because the file isn't even being created, and the part inside the for loop is executing with just 2's, 100 times.
#include <iostream>
#include <fstream>
using namespace std;
bool isPrime(int);
int main () {
ofstream outputFile;
int p = 2;
cout << "I will be giving you the first 100 prime numbers " << endl;
cout << "And giving you a file containing those numbers." << endl;
outputFile.open("PrimeNumbers100.txt");
for (int i = 2; i <= 100; i++)
{
isPrime(p);
cout << p << endl;
outputFile << p << endl;
}
outputFile.close();
cout << "You should now have the file." << endl;
/* int n;
int counter = 0;
int p = 2;
cout << "Welcome to prime counter. " << endl;
cout << "Which prime number would you like? ";
cin >> n;
while (counter < n) {
if (isPrime(p)) {
counter++;
}
p++;
}
p = p - 1;
cout << "Prime number " << n << " is " << p << "." << endl;
*/
return 0;
}
bool isPrime(int p) {
bool result = true;
if (p < 2) {
result = false;
}
else {
int stop = (int) (sqrt(p + .5));
for (int d = 2; d <= stop; d++) {
if (p % d == 0) {
result = false;
break;
}
}
}
return result;
}
Could someone please explain what I'm doing wrong here, and why it isn't even creating the file?
You initialize p at the top with 2. You should be calling isPrime with i instead.
You're getting 2s because you're printing out and storing p, but the loop is going over i.
Here is the updated code. Upon research I did find where it was saving the files, and there are instances of it just not working at all. However, This code runs and does give me everything I need it to.. Thank you for the tips, and I appreciate the very.... constructive feedback.
#include <iostream>
#include <fstream>
using namespace std;
bool isPrime(int);
int main () {
ofstream outputFile;
cout << "I will be giving you the first 100 prime numbers " << endl;
cout << "And giving you a file containing those numbers." << endl;
outputFile.open("PrimeNumbers100.txt");
for (int i = 2; i <= 100; i++)
{
if (isPrime(i)) {
outputFile << i << endl;
}
}
outputFile.close();
cout << "You should now have the file." << endl;
return 0;
}
bool isPrime(int p) {
bool result = true;
if (p < 2) {
result = false;
}
else {
int stop = (int) (sqrt(p + .5));
for (int d = 2; d <= stop; d++) {
if (p % d == 0) {
result = false;
break;
}
}
}
return result;
}
AT
4
5
6
7
#include<iostream>
#include<stdio.h>
#include <fstream>
using namespace std;
int main()
{
int data[4], a, b, c, d, e, f;
ifstream myfile;
myfile.open("tera.txt");
for (int i = 0; i < 4; i++)
{
myfile >> data[i];
}
myfile.close();
a = data[0];
b = data[1];
c = data[2];
d = data[3];
cout << a << "\t" << b << "\t" << c << "\t" << d << "\n";
return 0;
}
it takes AT also and give garbage value. how and where should i use ignore function to ignore AT Value.
And there is one thing more if there is another array given BT containing some value like this:
AT BT
how to store BT's all values under it in an array?
You just have to skip the first line. You can also add optional error handling, otherwise read may fail for all line.
if (!myfile)
{
cout << "can't open\n";
return 0;
}
string temp;
myfile >> temp;
cout << "first line: " << temp << endl;
for (int i = 0; i < 4; i++)
{
myfile >> data[i];
if (myfile.fail())
{
cout << "error\n";
myfile.clear();
myfile.ignore(1000000, '\n');
}
}
i wrote a simple program(C++) that take 20 numbers and sort them into ascending order.Now i want to save the actions in the program in a file like "num.txt" with . Can you explain me what changes should i do?
#include <iostream>
#include <iomanip>
#include <conio.h>
using namespace std;
int main() {
int x[21], s;
int j,i;
for (int i = 1; i < 21; i++)
{
cout << setw(11) << i << ": ";
cin >> x[i];
}
for (int i = 1; i < 21; i++)
{
for (int j = i+1; j < 21; j++)
{
if (x[j] < x[i])
{
s = x[j];
x[j] = x[i];
x[i] = s;
}
}
}
cout << endl;
for (int i = 1; i < 21; i++)
{
cout << i << ": ";
cout << x[i] << "\t";
if (i % 5 == 0)
{
cout << endl;
}
}
getch();
return 0;
}
i know it's simple but i just started since few days ago and i'm novice.
To output the numbers to a file you can use std::ofstream for the output stream and replace cout with the variable name you use for the stream.
std::ofstream outfile;
outfile.open("num.txt");
for (int i = 1; i < 21; i++)
{
outfile << i << ": ";
outfile << x[i] << "\t";
if (i % 5 == 0)
{
outfile << std::endl;
}
}
outfile.close();
You can also take it a step further and add input validation and use components from the Standard Library to handle most of what you are trying to accomplish. For instance instead of storing the numbers in an array I suggest using std::vector instead. You can also use std::sort to sort the data instead of implementing it yourself.
#include <vector> // vector
#include <fstream> // fstream
#include <algorithm> // sort
#include <iostream>
int main()
{
std::vector<int> numbers;
while(numbers.size() != 20)
{
int value;
if(!(std::cin >> value))
{
std::cout << "you must enter a number" << std::endl;
}
else
{
numbers.push_back(value);
}
}
// Do the sort. Pretty easy huh!
std::sort(numbers.begin(), numbers.end());
std::ofstream outfile;
outfile.open("num.txt");
if(outfile.is_open() == false)
{
std::cout << "Unable to open num.txt" << std::endl;
}
else
{
for(size_t i = 0; i < numbers.size(); i++)
{
outfile << i << ": ";
outfile << numbers[i] << "\t";
if (i % 5 == 0)
{
outfile << std::endl;
}
}
outfile.close();
}
}
Use this in your code
#include <fstream>
ofstream outputFile;
outputFile.open("outputfile.txt");
outputFile << value << endl;
outputFile.close();
One solution is to use ofstream (in "fstream.h", very similar to std::cout):
ofstream out("num.txt");
if (out.is_open() == false)
{
cout << "Error! Couldn't open file!" << endl;
}
else
{
out << "\n";
for (int i = 1; i < 21; i++)
{
out << i << ": ";
out << x[i] << "\t";
if (i % 5 == 0)
{
out << "\n";
}
}
out.close();
}
If you're running your program from the command line, type the following(when you run it) to forward the output to a file:
myApp > num.txt
you can also use the < switch to specify a file to get input from too
You can find more information here.
here is your code with all the changes
now you just need to copy paste (i have made a comment on line i added )
#include <iostream>
#include <iomanip>
#include <conio.h>
#include <fstream>//file stream
using namespace std;
int main() {
int x[21], s;
int j,i;
for (int i = 1; i < 21; i++)
{
cout << setw(11) << i << ": ";
cin >> x[i];
}
for (int i = 1; i < 21; i++)
{
for (int j = i+1; j < 21; j++)
{
if (x[j] < x[i])
{
s = x[j];
x[j] = x[i];
x[i] = s;
}
}
}
ofstream out; //output file stream
out.open("num.txt"); //opening (and creating output file named out
//cout << endl;
for (int i = 1; i < 21; i++)
{
//cout << i << ": ";
out << i << ": "; //printing in output file
// cout << x[i] << "\t";
out << x[i] << "\t"; //printing in output file
if (i % 5 == 0)
{
//cout << endl;
out << endl; //printing in output file
}
}
//getch();
out.close(); //closing output file
return 0;
}