Im having issues with my code. Im trying to get it to read from my input file. t
ID: 3665527 • Letter: I
Question
Im having issues with my code. Im trying to get it to read from my input file. the input file is just various words. Here is my code, my output file works fine. But I get so many errors trying to read from my input file in the loops.
using namespace std;
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
void put(string word, string words[], int counts[], int & size)
{
int w;
for (w = 0; w < size && word >= words[w]; w++);
if (w >= size) {
words[w] = word;
counts[w] = 1;
++size;
}
else if (word < words[w]) {
for (int i = size - 1; i >= w; i--) {
words[i + 1] = words[i];
counts[i + 1] = counts[i];
}
words[w] = word;
counts[w] = 1;
++size;
}
else {
counts[w] = counts[w] + 1;
}
}
int main() {
ifstream input("input.txt");
ofstream wout("wordscounts.txt");
string word;
int inputSize = sizeof(input) / sizeof(string);
int counts[100];
const int MAX = 100;
string words[MAX];
int wordsSize = 0;
while(input << word)
put(input[word], words, counts, wordsSize);
wout << " Word Frequency" << endl;
for (word = 0; word < inputSize; ++word) {
wout << setw(10) << words[word] << setw(4) << counts[word] << endl;
}
input.close();
wout.close();
return 0;
}
Explanation / Answer
using namespace std;
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
void put(string word, string words[], int counts[], int & size)
{
int w;
for (w = 0; w < size && word >= words[w]; w++);{
if (w >= size) {
words[w] = word;
counts[w] = 1;
++size;
}
else if (word < words[w]) {
for (int i = size - 1; i >= w; i--) {
words[i + 1] = words[i];
counts[i + 1] = counts[i];
}
words[w] = word;
counts[w] = 1;
++size;
}
else {
counts[w] = counts[w] + 1;
}}
}
int main() {
ifstream input("input.txt");
ofstream wout("wordscounts.txt");
string word;
int inputSize = sizeof(input) / sizeof(string);
int counts[100];
const int MAX = 100;
string words[MAX];
int wordsSize = 0;
while(input << word)
put(input[word], words, counts, wordsSize);
wout << " Word Frequency" << endl;
for (word = 0; word < inputSize; ++word) {
wout << setw(10) << words[word] << setw(4) << counts[word] << endl;
}
input.close();
wout.close();
return 0;
}