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.
Related
This file is not opening for a reason which I don't know really, any insight?
#include <iostream>
#include <string>
#include <algorithm>
#include <fstream>
#include <cctype>
using namespace std;
.
.
.
.
.
void MinHeap::TopKFrequentWord(string fileName, int k)
{
MinHeap mh;
Trie T;
string word;
string line;
ifstream inFile(fileName);
for (int i = 0; i < 22; i++)
{
if (i >= 10)
{
fileName = "C:\\Users\\Kareem's Laptop\\Desktop\\Reuters-21578\\reut2-0" + to_string(i) + ".sgm";
}
else if (i <= 9)
{
fileName = "C:\\Users\\Kareem's Laptop\\Desktop\\Reuters-21578\\reut2-00" + to_string(i) + ".sgm";
}
if (!inFile)
{
cout << fileName << " did not open." << endl;
exit(1);
}
bool found = true;
while (inFile >> line)
{
size_t pos = line.find("<BODY>");
if (pos != string::npos)
{
if (found)
{
word = line.substr(pos + 6);
found = true;
TrieNode* TN = T.search(word);
if (!TN)
{
TN = T.insert(word);
}
else
{
TN->frequency++;
}
mh.insert(TN, word);
}
}
}
mh.Display();
cout << '\n';
inFile.close();
}
}
int main()
{
MinHeap foo;
string fileName;
foo.TopKFrequentWord(fileName, 10);
return 0;
}
I have to open 21 files in a loop, read them all and print out the top 10 word count for all of those words.
Unable to use vector due to instructions. I apologize if similarities are obvious.
I tried putting all files in an array but it still didn't work. No errors just not opening (getting exit(1) command).
You are opening the file before the loop. Since you are updating the filename variable inside the loop, I suppose you want to open it each time you pass through the loop.
Move the line :
ifstream inFile(fileName);
to one line before the test:
if (!inFile)
Also, the place where you code ifstream inFile(fileName); you have an empty string in fileName (You didn't initialize the variable passed as argument in main).
Also, you are passing a int k parameter to the function but never uses it there.
#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;
}
}
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
I'm a physics PhD student with some experience coding in java, but I'm trying to learn C++.
The problem I'm trying to solve is to read in data from a .txt file and then output all the numbers > 1000 in one file and all those <1000 in another.
What I need help with is writing the part of the code which actually reads in the data and saves it to an array. The data itself is only separated by a space, not all on a new line, which is confusing me a bit as I don't know how to get c++ to recognise each new word as an int. I have canabalised some code I have got from various sources online-
#include <iostream>
#include <string>
#include <fstream>
#include <cstring>
#include<cmath>
using namespace std;
int hmlines(ifstream &a) {
int i=0;
string line;
while (getline(a,line)) {
cout << line << endl;
i++;
}
return i;
}
int hmwords(ifstream &a) {
int i=0;
char c;
a >> noskipws >> c;
while ((c=a.get()) && (c!=EOF)){
if (c==' ') {
i++;
}
}
return i;
}
int main()
{
int l=0;
int w=0;
string filename;
ifstream matos;
start:
cout << "Input filename- ";
cin >> filename;
matos.open(filename.c_str());
if (matos.fail()) {
goto start;
}
matos.seekg(0, ios::beg);
w = hmwords(matos);
cout << w;
/*c = hmchars(matos);*/
int RawData[w];
int n;
// Loop through the input file
while ( !matos.eof() )
{
matos>> n;
for(int i = 0; i <= w; i++)
{
RawData[n];
cout<< RawData[n];
}
}
//2nd Copied code ends here
int On = 0;
for(int j =0; j< w; j++) {
if(RawData[j] > 1000) {
On = On +1;
}
}
int OnArray [On];
int OffArray [w-On];
for(int j =0; j< w; j++) {
if(RawData[j]> 1000) {
OnArray[j] = RawData[j];
}
else {
OffArray[j] = RawData[j];
}
}
cout << "The # of lines are :" << l
<< ". The # of words are : " << w
<< "Number of T on elements is" << On;
matos.close();
}
But if it would be easier, i'm open to starting the whole thing again, as I don't understand exactly what all the copied code is doing. So to summarise, what I need is it to-
Ask for a filepath in the console
Open the file, and store each number (separated by a space) as an element in a 1D array
I can manage the actual operations myself I think, if I could just get it to read the file the way I need.
Thanks very much
Using C++11 and the Standard Library makes your task fairly simple. This uses Standard Library containers, algorithms, and one simple lambda function.
#include <algorithm>
#include <iostream>
#include <iterator>
#include <fstream>
#include <string>
#include <vector>
int main()
{
std::string filename;
std::cout << "Input filename- ";
std::cin >> filename;
std::ifstream infile(filename);
if (!infile)
{
std::cerr << "can't open " << filename << '\n';
return 1;
}
std::istream_iterator<int> input(infile), eof; // stream iterators
std::vector<int> onvec, offvec; // standard containers
std::partition_copy(
input, eof, // source (begin, end]
back_inserter(onvec), // first destination
back_inserter(offvec), // second destination
[](int n){ return n > 1000; } // true == dest1, false == dest2
);
// the data is now in the two containers
return 0;
}
Just switch the type of variable fed to your fistream, created from new std:ifstream("path to file") into a int and c++ will do the work for you
#include <fstream> //input/output filestream
#include <iostream>//input/output (for console)
void LoadFile(const char* file)
{
int less[100]; //stores integers less than 1000(max 100)
int more[100]; //stores integers more than 1000(max 100)
int numless = 0;//initialization not automatic in c++
int nummore = 0; //these store number of more/less numbers
std::ifstream File(file); //loads file
while(!file.eof()) //while not reached end of file
{
int number; //first we load the number
File >> number; //load the number
if( number > 1000 )
{
more[nummore] = number;
nummore++;//increase counter
}
else
{
less[numless] = number;
numless++;//increase counter
}
}
std::cout << "number of numbers less:" << numless << std::endl; //inform user about
std::cout << "number of numbers more:" << nummore << std::endl; //how much found...
}
This should give you an idea how should it look like(you shoudnt use static-sized arrays tough) If you got any probs, comment back
Also, please try to make nice readable code, and use tabs/ 4 spaces.
even though its pure C, this might give you some hints.
#include <stdio.h>
#include <stdlib.h>
#include "string.h"
#define MAX_LINE_CHARS 1024
void read_numbers_from_file(const char* file_path)
{
//holder for the characters in the line
char contents[MAX_LINE_CHARS];
int size_contents = 0;
FILE *fp = fopen(file_path, "r");
char c;
//reads the file
while(!feof(fp))
{
c = fgetc(fp);
contents[size_contents] = c;
size_contents++;
}
char *token;
token = strtok(contents, " ");
//cycles through every number
while(token != NULL)
{
int number_to_add = atoi(token);
//handle your number!
printf("%d \n", number_to_add);
token = strtok(NULL, " ");
}
fclose(fp);
}
int main()
{
read_numbers_from_file("path_to_file");
return 0;
}
reads a file with numbers separated by white space and prints them.
Hope it helps.
Cheers
I'm writing a program in c++ and I need to ask the user for a file name, print the file and then reprint it with every 5th word missing. I've gotten as far as to asking them file name, checking for errors and printing out the file, I'm just completely lost on how to reprint it with every 5th word missing, any help?
#include <iostream>
#include <fstream>
#include <cctype>
#include <string>
using namespace std;
int main()
{
const int SIZE = 51;
char fileName[SIZE];
char ch;
ifstream inFile;
bool lastWasLetter = true;
const string UNDERLINE = "__________";
cout << "Please enter a file name: ";
cin >> fileName;
inFile.open (fileName, ios::in);
while (!inFile)
{
cout << fileName << " could not be opened, please enter new file name: ";
cin >> fileName ;
inFile.open (fileName, ios::in);
}
inFile.clear(); // reset read pointer to very beginning of file
inFile.seekg(0L, ios::beg);
std::string word;
int count = 0;
while (inFile >> word)
{
count++;
if (count % 5 != 0)
cout << word << endl;
}
}
And yes this a project I'm working on for my programming class.
Just keep track of the number of words you've read and skip printing every 5th word, i.e. whenever the word count is a multiple of 5. For example:
std::string word;
int count = 0;
while (inFile >> word) {
count++;
if (count % 5 != 0)
cout << word << endl;
}