I am having an error message that i cant figure out how ti get rid of. I am trying to have my program ask the user for the file name and then output a list of prime numbers from 1 - 100 to that file. I can get it to work if the file is an "ofstream outputfile;" that I specify but when I change it to an input file the error pops up. It is on line 28 right after inputFile. I have checked other questions on this and they all say to include the header which I have done but it still doesn't fix the issue. I am new to programming so I appreciate your help and patience.
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
bool isPrime(int);
int main()
{
ifstream inputFile;
string filename;
cout << "Enter a filename: ";
cin >> filename;
inputFile.open(filename);
for (int i = 1; i <= 100; i++)
{
isPrime(i);
while (isPrime(i) == true)
{
inputFile << i << endl; //ERROR IS HERE!
break;
}
}
inputFile.close();
system("pause");
return 0;
}
bool isPrime(int n)
{
bool isPrime = true;
for (int i = 2; i<n; i++)
{
double x = n%i;
if (x == 0.0)
isPrime = false;
}
return isPrime;
}
In C++ operator << is user for output to output streams (like std::ofstream), and operator >> is used for input streams (like std::ifstream).
So, replacing ifstream to ofstream will fix this.
If you want to write something in the file
Instead of declaring an ifstream object declare a ofstream object that will fix your problem
Related
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream ticket ("numbers.txt");
bool isCovered[99];
int number;
for (int i = 0; i < 99; i++)
isCovered[number] = false;
// Read each number and mark its corresponding element covered
ticket >> number;
while (number != 0)
{
isCovered[number - 1] = true;
ticket >> number;
}
// Check if all covered
bool allCovered = true; // Assumes all covered initially
for (int i = 0; i < 99; i++)
if (!isCovered[i])
{
allCovered = false; //Finds one number not covered
break;
}
return 0;
I know i may have confused you all with the last question i posted but this time i understand the concepts and have an even better question. How can i display the number of occurrences using a txt file in fstream while using C++? And how would i properly use my for and if loops for said problem, thanks?
Update: Got the numbers from the text file to display as well as numbers 1 - 99. But how do i code for the number of occurrences?
#include <fstream>
#include <string>
using namespace std;
int main()
{
int i;
// Open the text file in the system
ifstream infile;
infile.open("numbers.txt");
if(infile.fail())
{
cout << "This file does not work";
}
else{
string s;
while(infile >> s){
cout << s << endl;
}
}
// Display all numbers 1 through 99
for (i = 1; i < 99; i++){
cout << i << endl;
}
}
my assignment asks me to open a text file and output a random array and loop it back to the question. I am wondering as why my code has no output? I appreciate all the help I get. Thank you very much.
#include <iostream>
#include <cstdlib>
#include <string>
#include <fstream>
#include <ctime>
using namespace std;
int main()
{
srand(time(0));
ifstream fin;
fin.open("songs.txt");
if (!fin.good()) throw "I/O error";
string ans;
const int MAX_SONGS = 200;
int nSongs=0;
string song[MAX_SONGS];
while (fin.good())
{
// read txt file
string aSong;
getline(cin, aSong);
// add song if still have space
if (nSongs < MAX_SONGS)
song[nSongs++] = aSong;
}
fin.close();
cout<<"hi!";
for (int i=0; i<nSongs; i++)
{
song[i] = (rand() % nSongs);
cout << " play a song [Y/N]? ";
getline(cin, ans);
if (ans=="Y"||ans=="y")
cout << song[i]<<endl;
break;
if (ans=="n"||ans=="N")
break;
}
}
When you read in the file, you are using cin instead of fin so you end up reading from the keyboard instead.
getline(cin, aSong); // getline(fin,aSong)
Normally if the file is just a regular text file with newlines you write it more compact
string aSong;
while ( fin >> aSong )
{
if (nSongs < MAX_SONGS)
song[nSongs++] = aSong;
}
This form
while (fin.good())
is wrong, because the bit indicating error is set after you do getline but you still continue after getline failed.
if (nSongs < MAX_SONGS)
song[nSongs++] = aSong;
When you open the file, use the following syntax instead
ifstream fin("songs.txt");
if (fin)
{
...
}
or if you want to keep they way you had it
if (!fin)
{
throw "I/O error";
}
EDIT:
song[i] = (rand() % nSongs);
should be
int j = (rand() % nSongs);
...
if (ans == "Y" || ans == "y")
{
cout << song[j] << endl;
if you wanted to show a random song.
Hey guys I stuck working on an assignment in which I asked to write a program that lists the contents of a file.
#include<iostream>
#include<fstream>
using namespace std;
int main() {
string array[5];
ifstream infile("file_names.txt");
int x=0;
while(infile>>array[x++]){
for(int i=0;i<=x;i++){
infile >> array[i];
cout << array[i] << endl;}}
}
basically I have a file named "file_names.txt" that contains three strings and I want my program to list them.
you don't need two loops.
int main() {
int array_size=5;
string array[array_size];
ifstream infile("file_names.txt");
int x=0;int i=0;
while(i<array_size && infile>>array[i]){ //order is important here
cout << array[i] << endl;
i++;
}
}
Your assignment was
an assignment in which I asked to write a program that lists the contents of a file.
One way of printing the contents of a file could be
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream fin("my_file.txt", ios::in); // open input stream
if(!fin){ // check state, that file could be successfully opened
printf("Error opening file.");
return 1;
}
while(fin.peek() != EOF){
cout << (char)fin.get();
}
fin.close(); // close input stream
return 0;
}
This code demonstrates some basic C++ functionality like
opening an input stream, checking the state of the input stream and reading the contents character by character. Try to understand each step.
I know I can get to the same result like this
string array[50];
ifstream infile("file_names.txt");
for(int i=0; **i<3**; i++){
infile >> array[i];
cout << array[i] <<endl;}
But the whole point is to use a while loop because there might be more or less than 3 items
I'm doing a lab in university that multiplies out 2 matrices from 2 different files and in one of the questions i've been asked to print the results on the console (which is not a problem, it's already done) but printing it to a new save file is the problem.
i'm fairly new to c++ so i apologize in advance if the mistake is obvious :(
here is my code so far....
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
///////// my output file /////////////
string outfile1, save;
cout<<"Please enter the name of the file you want to save the results in"<<endl;
cin>>outfile1;
ofstream outfile(outfile1.c_str());
if(!outfile)
{
cout<<"Please drag in the right file you want the results to be saved on"<<endl;
system("PAUSE");
return -1;
}
/////// sitting up the first matrix file ////////
string matrixA;
cout<< "Please drag file (matrix1) into this window"<<endl;
cin>>matrixA;
ifstream infile;
infile.open(matrixA.c_str());
if(!infile)
{
cout<<"ERROR: Wrong file, please try restart program and try again."<<endl;
return -1;
}
string matrix1;
int a[5][5];
for (int i = 0; i<5;i++)
{
for(int j = 0;j<5;j++)
{
getline(infile,matrix1,',');
a[i][j]= stoi(matrix1);
cout<< a[i][j]<<" ";
}
cout<<endl;
}
infile.close();
/////// sitting up the 2nd matrix file ////////
string matrixB;
cout<< "Please drag file (matrix2) into this window"<<endl;
cin>>matrixB;
ifstream infile2;
infile2.open(matrixB.c_str());
if(!infile2)
{
cout<<"ERROR: Wrong file, please try restart program and try again."<<endl;
return -1;
}
string matrix2;
int b[5][5];
for (int k = 0; k<5;k++)
{
for(int l = 0;l<5;l++)
{
getline(infile2,matrix2,',');
b[k][l]= stoi(matrix2);
cout<< b[k][l]<<" ";
}
cout<<endl;
}
infile2.close();
////////////// CALCULATIONS //////////////////////
cout<<"The product of both matrices is: "<<endl;
int result[5][5];
while (outfile1)
for (int x = 0; x < 5; x++)
{
for (int y = 0; y < 5; y++)
{
result[x][y] = 0;
for(int z = 0; z < 5; z++)
{
result[x][y] += a[x][z]*b[z][y];
}
cout << result[x][y] <<" ";
outfile1<< result[x][y]<<" "; // <<---------- why can i not do this?
}
cout<<endl;
}
system("PAUSE");
return 0;
}
is there an easier way to do it? if i try to run the code as it is, it gives me a highlight under the first "<<" saying (no operator "<<" matches these operands)
outfile1<<result[x][y]<<" ";
Your program doesn't compile because of two reasons.
while (outfile1)
outfile1 is an std::string (the output file name) and is not convertible to bool. It's not quite clear what you tried to achieve with this code.
outfile1<< result[x][y]<<" ";
Again, outfile1 is an std::string. Your output stream is outfile, so you should change this to
outfile << result[x][y] << " ";
outfile1 is of type string, while outfile is of type ofstream. Change outfile1 to be outfile on lines 86 and 100 and it should compile as expected.
You may want to name your variables differently to help prevent errors like this, perhaps naming outfile1 as outfileName.
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <fstream>
using namespace std;
void make_array(ifstream& num, int (&array)[50]);
int main()
{
ifstream file; // variable controlling the file
char filename[100]; /// to handle calling the file name;
int array[50];
cout << "Please enter the name of the file you wish to process:";
cin >> filename;
cout << "\n";
file.open(filename);
if (file.fail()) {
cout << "The file failed to open.\n";
exit(1);
} else {
cout << "File Opened Successfully.\n";
}
make_array(file, array);
file.close();
return (0);
}
void make_array(ifstream& num, int (&array)[50])
{
int i = 0; // counter variable
while (!num.eof() && i < 50) {
num >> array[i];
i = i + 1;
}
for (i; i >= 0; i--) {
cout << array[i] << "\n";
}
}
I am trying to read values from a file to an array using fstream. When I try to display the contents of the array, I get 2 really big negative numbers, and then the contents of the file.
Any ideas what I did wrong?
Your use of num.get(array[i]) doesn't match any of its signatures. See get method description. What you want is this:
array[i] = num.get();
As discussed in the comments, you try to read an integer which is encoded as text. For this, you need to use operator>> (which reads any type encoded as string) instead of get (which reads a single byte):
num >> array[i];