read text file then add character to list? - c++

So I'm trying to complete this part of a program where I have to read a text file from Stdin and add it to the 'word list' wl. I get how to read from a text file but I don't know how to go about adding 'words' to a list, if that makes sense. So here's what I got:
string getWord(){
string word;
while (cin >> word){
getline(cin, word);
}
return word;
}
void fillWordList(string source[], int &sourceLength){
ifstream in.file;
sourceLength = 50;
source[sourceLength]; ///this is the part I'm having trouble on
Source is an array that determines how many words are read from the text and length is the amount printed on screen.
Any ideas on what I should begin with?
EDIT: Here's the program I'm writing the implementation for:
#include <iostream>
#include <string>
#include <vector>
#include "ngrams.h"
void help(char * cmd) {
cout << "Usage: " << cmd << " [OPTIONS] < INPUTFILE" << endl;
cout << "Options:" << endl;
cout << " --seed RANDOMSEED" << endl;
cout << " --ngram NGRAMCOUNT" << endl;
cout << " --out OUTPUTWORDCOUNT" << endl;
}
string source[250000];
vector<string> ngram;
int main(int argc, char* argv[]) {
int n, outputN, sl;
n = 3;
outputN = 100;
for (int i = 0; i < argc; i++) {
if (string(argv[i]) == "--seed") {
srand(atoi(argv[i+1]));
} else if (string(argv[i]) == "--ngram") {
n = 1 + atoi(argv[i+1]);
} else if (string(argv[i]) == "--out") {
outputN = atoi(argv[i+1]);
} else if (string(argv[i]) == "--help") {
help(argv[0]);
return 0; }
}
fillWordList(source,sl);
cout << sl << " words found." << endl;
cout << "First word: " << source[0] << endl;
cout << "Last word: " << source[sl-1] << endl;
for (int i = 0; i < n; i++) {
ngram.push_back(source[i]);
}
cout << "Initial ngram: ";
put(ngram);
cout << endl;
for (int i = 0; i < outputN; i++) {
if (i % 10 == 0) {
cout << endl;
}
//put(ngram);
//cout << endl;
cout << ngram[0] << " ";
findAndShift(ngram, source, sl);
} }
I'm supposed to use this as a reference but it dosen't help me too much.

Declaring raw array requires the size of the array to be a compile-time constant. Use std::vector or at least std::array instead. And pass source by reference if you want to fill it.

Related

I want this c++ program to find the the words starting with user entereed letter and print them using a new function

I want this c++ program to find the the words starting with user entereed letter and print them using a new function.but the thins is that it only finds 1st letter for the second time it runs ina loop and then , i dont know what happens ... I am a beginner please help me!
uncomment the line that are necessary
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
void getUserInput(string *filename, string *find)
{
cout << "file name : ";
cin >> *filename;
cout << "required character : ";
cin >> *find;
}
string* processFile(string fileName, string word, int *t, int *w, string found[])
{
fstream file;
int countIn = 0,
totaal = 0;
int *count = &countIn;
int *total = &totaal;
int i = 0;
string find; // the max length of the file should not exceed this value is if does please change it here.
file.open(fileName, ios::in);
if (file.is_open())
{
while (!file.eof())
{
file >> find;
totaal++;
if (word == find)
{
char a[100];
int s = find.size();
for (int j = 0; i < find.size(); j++)
{
string(1, find[i]);
}
found[i] = find;
i++;
countIn++;
}
}
}
else
cout << "!!!!invalid file name!!!!\n";
file.close();
//for (int i = 0, j = 0; i < totaal; i++)
//{
//
// cout << find[i] << '\t' << find[i][0] << endl;
//
// if (word == find[i][0])
// {
// cout << "i is " << i << endl;
// cout << "j is " << j << endl;
// cout << "Calculated i and j\n";
// found[j] = find[i];
// cout << "found[j] " << found[j] << "\nfind[i] " << find[i] << endl;
// j++;
// countIn++;
// cout << "Inside if\n";
// }
// cout << "outsidenside if\n";
//}
*t = *total;
*w = *count;
//cout << countIn << endl << totaal << endl;
//cout << *count << endl << *total<<endl;
return found;
}
void displayOutput(int total, int count, string wordlist[])
{
cout << "Total words in the file: " << total;
if (count != 0)
{
cout << "\nTotal " << count << " related words found in the file\n";
for (int i = 0; i < count; i++)
cout << i + 1 << "\t" << wordlist[i] << endl;
}
else
cout << "No matching case found\n";
}
int main()
{
string nameoffile;
string wordtofind;
string *ptr1 = &nameoffile;
string *ptr2 = &wordtofind;
string foundwords[] = { "" };
int occur = 0,
totalWords = 0;
int *occ = &occur;// occurence of the certain word
int *tot = &totalWords;// total wods in the file
getUserInput(ptr1, ptr2);
processFile(nameoffile, wordtofind, occ, tot, foundwords); //calling the processing function
displayOutput(occur, totalWords, foundwords);
return 0;
}

Option to print output to screen or given file name (c++)

I would like option 2 to pass the output to a typed file name. However, the program is creating the file but not passing the output to the file. I think just using ostream is fine here, but don't know how to go about it.
void displayTable(int n, char op) {
int printOption;
string outputFileName;
ofstream createOutputFile;
while (true) { //option for print screen or print to file
cout << "Select: \n1) Print on Screen \n2) Print to a file name \nSelection: ";
cin >> printOption;
if (printOption == 1)
break;
else if (printOption == 2){
cout << "Type in the name for the output file." << endl;
cin >> outputFileName;
createOutputFile.open(outputFileName);
break;
}
else
cout << "Please enter a valid number." << endl;
}
int max = getMaxSize(n, op);
cout << setw(max) << op << "|";
for (int i = 1; i <= n; ++i) {
cout << setw(max) << i;
}
cout << endl;
for (int i = 0; i < max; ++i) {
cout << "-";
}
cout << "+";
for (int i = 0; i < n * max; ++i) {
cout << "-";
}
cout << endl;
for (int i = 1; i <= n; ++i) {
cout << setw(max) << i << "|";
for (int j = 1; j <= n; ++j) {
cout << setw(max) << getValue(i, j, op);
}
cout << endl;
}
cout << endl;
createOutputFile.close();
}
You are not printing anything to createOutputFile, everything is being printed to cout instead. That is why to don't see anything in the file, and everything in the console.
The easiest way to solve your issue is to redirect cout to createOutputFile's output buffer, eg:
auto cout_buff = cout.rdbuf();
...
createOutputFile.open(outputFileName);
cout.rdbuf(createOutputFile.rdbuf())
// all cout outputs will now go to the file...
...
cout.rdbuf(cout_buff); // restore when finished...
Otherwise, move your print logic to a separate function that takes an ostream& as a parameter:
void doMyLogic(ostream &os)
{
// print to os as needed...
}
...
if (printOption == 1) {
doMyLogic(cout);
break;
}
if (printOption == 2) {
...
ofstream createOutputFile(outputFileName);
doMyLogic(createOutputFile);
break;
}
...

Converting String to vector of Integers

FizzBuzz program. The user enters numbers separated by a comma. The program reads input and lets the computer know if divisible by 3, 5 or both. When the user enters 15,5,30, the program will only output the first number, 15 and stops there. What am I doing wrong?
void processVector(vector<int> intVector)
{
bool loop;
for (int i = 0; i < intVector.size(); i++)
{
loop = true;
}
}
int main()
{
cout << "Welcome to the FizzBuzz program!" << endl;
cout << "This program will check if the number you enter is divisable by
3, 5, or both." << endl;
cout << "Please enter an array of numbers separated by a comma like so,
5,10,15" << endl;
cin >> userArray;
vector<int> loadVector(string inputString);
istringstream iss(userArray);
vector <int> v;
int i;
while (iss >> i);
{
v.push_back(i);
if (iss.peek() == ',')
iss.ignore();
if (i % 15 == 0)
{
cout << "Number " << i << " - FizzBuzz!" << endl;
}
else if (i % 3 == 0)
{
cout << "Number " << i << " Fizz!" << endl;
}
else if (i % 5 == 0)
{
cout << "Number " << i << " Buzz!" << endl;
}
else
{
cout << "Number entered is not divisable by 3 or 5." << endl;
}
}
system("pause");
}
Here is how I would approach the problem:
#include <iostream>
#include <string>
#include <vector>
int main() {
std::cout << "!!!Hello World!!!" << std::endl; // prints !!!Hello World!!!
std::cout << "Please enter your numbers seperated by a comma (5, 3, 5, 98, 278, 42): ";
std::string userString;
std::getline(std::cin, userString);
std::vector<int> numberV;
size_t j = 0; // beginning of number
for(size_t i = 0; i < userString.size(); i++){
if((userString[i] == ',') || (i == userString.size() -1)){ // could also use strncmp
numberV.push_back(std::stoi(userString.substr(j, i))); // stoi stands for string to int, and .substr(start, end) creates a new string at the start location and ending at the end location
j = i + 1;
}
}
for(size_t n = 0; n < numberV.size(); n++){
std::cout << numberV[n] << std::endl;
}
return(0);
}
This should give you a method to solve the problem (without handling the fizzbuzz part of your program) that I personally find simpler.
The basic form for using functions is:
<return type> <function_name(<inputs)>{
stuff
};
So, a basic function that takes a string and returns a vector (what you are wanting) would be:
std::vector myStringToVector(std::string inputString){
std::vector V;
// your code (see the prior example for one method of doing this)
return(V);
};
It also looks like they want a separate function for outputting your vector values, this could look something like:
void myVectorPrint(std::vector inputVector){
// your code (see prior example for a method of printing out a vector)
};
Thank you #Aaron for the help. Here is the finished code and it works great!
I had to take a little more time researching a few things and trying to understand which order and what to put where in terms of the functions and how to call them. I appreciate all the help as I said I am a noob.
#include "stdafx.h"
#include <iostream>
#include<sstream>
#include<string>
#include<vector>
using namespace std;
vector<int> loadVector(string inputString)
{
stringstream ss(inputString);
vector <int> numberV;
int n;
size_t j = 0; // beginning of number
for (size_t n = 0; n < inputString.size(); n++)
{
if ((inputString[n] == ',') || (n == inputString.size() - 1))
{
numberV.push_back(std::stoi(inputString.substr(j, n)));
j = n + 1;
}
}
return numberV;
}
void processVector(vector<int> intVector)
{
for (int i = 0; i < intVector.size(); i++)
{
int n = intVector.at(i);
if (n % 15 == 0)
{
cout << "Number " << n << " - FizzBuzz!" << endl;
}
else if (n % 3 == 0)
{
cout << "Number " << n << " Fizz!" << endl;
}
else if (n % 5 == 0)
{
cout << "Number " << n << " Buzz!" << endl;
}
else
{
cout << "Number entered is not divisable by 3 or 5." << endl;
}
}
}
int main()
{
cout << "Welcome to the FizzBuzz program." << endl
<< "Please enter an array of numbers separated by comma's (5, 10, 15)"
<< endl;
string inputString;
getline(cin, inputString);
try
{
vector<int> intVector = loadVector(inputString);
processVector(intVector);
}
catch (const exception& e)
{
cout << "Exception caught: '" << e.what() << "'!;" << endl;
}
system("pause");
return 0;
}

Arrays comparison (.Txt file to user input) C++

This is a program that is suppose to compare an answer sheet (which is a .txt file) to user input. Meaning I'm comparing two arrays but I'm having a PITA time making it work. It complies just fine but it just does not compare the user input array to the .txt file array and counts everything as wrong even when I manually put in the correct answers on the user input side. Any advice or suggestions would be appreciated! PS: I cannot use vectors, only arrays. That's not a personal choice but a requirement.
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
const int CHOICE = 20;
const char KEY = 20;
char correctAnswers[KEY];
char A, B, C, D;
char userAnswers[CHOICE];
char rightOrWrong[CHOICE];
int totalMissed;
int sum = 0;
int count = 0;
ifstream inputFile;
inputFile.open("CorrectAnswers.txt");
while (count < KEY && inputFile >> correctAnswers[count])
count++;
inputFile.close();
for (int qst = 0; qst < 20; qst++)
{
cout << "Please put an answer for the question: " << endl;
cin >> userAnswers[qst];
cout << endl;
if (userAnswers[qst] == correctAnswers[qst])
{
rightOrWrong[qst] = 'C';
}
else
{
rightOrWrong[qst] = 'I';
}
}
for (int qst = 0; qst < 20; qst++)
{
if (rightOrWrong[qst] == 'C')
{
sum += 1;
}
else
{
cout << "Answer #" << qst << " is not correct" << endl;
}
}
totalMissed = 20 - sum;
cout << "This is your final score: " << endl;
cout << "You missed " << (20 - sum) << "/20 of the questions" << endl;
cout << "You overall percentage is " << (sum / 20) << "%." << endl;
if (sum < 14 && sum >= 0)
{
cout << "You have not passed the exam. You must have a 70% or higher to pass. Study harder next time!" << endl;
}
else
{
cout << "Pat yourself on the back! You've passed the test!" << endl;
}
return 0;
}
I apologize if this looks crappily formatted, it doesn't look like this normally.

How to read a input file in an array in c++

I'm trying to store hexadecimal values into some form of an array from a file then change those numbers to binary. So far the program I wrote is only collects the last value. The file looks something like this. note(a 1 or 0 is before each hex value)
1 408ed4
0 10019d94
0 408ed8
1 10019d88
0 408edc
0 1001322
My code is #include
#include <fstream>
#include <string>
#include <cstdlib>
#include <bitset>
#include <sstream>
#define MAX_ADDRESSES 1000000
using namespace std;
int main(int argc, char **argv) {
//Declare variables
int szL1 = atoi(argv[2]);
int szL2 = atoi(argv[4]);
string type = argv[6]; //Determines the type of cache
//string fileN = argv[7];
int info, i = 1, j = 1; //info is what is read in, i & j are testing variables
string *rd_add = new string[MAX_ADDRESSES]; //set the max string length for what's read
string *wrt_add = new string[MAX_ADDRESSES]; //set the max string length for what's written
int total = 0; //total # of reads/writes
int rds = 0; //base # of reads
int wrt = 0; //base # of writes
int array_size = 1001024;
char *array = new char[array_size];
int position = 0;
ifstream fin("big_trace.txt");//open big trace file********
if (fin.is_open()){
cout << "File opened successfully" << endl;
while (!fin.eof() && position < array_size){
fin.get(array[position]);
position++;
}
array[position - 1] = '\0';
for (int x = 0; array[x] != '\0'; i++){
cout << array[i];
}
}
else{
cout << "File could not be opened" << endl;
}
//check for a power of 2 for szL1
while (1)
{
if (i == szL1)
break;
//Error Message
else if (i > szL1)
{
cout << "Error. sizeL1 must be a power of 2. Please try again." << endl << endl;
return 0;
}
i *= 2;
}
//cout << "size1 " << szL1 << endl;
//check for a power of 2 for szL2
while (1)
{
if (j == szL2)
break;
//Error
else if (j > szL2)
{
cout << "Error. sizeL2 must be a power of 2. Please try again." << endl << endl;
return 0;
}
j *= 2;
}
//cout << "size2 " << szL2 << endl;
//Check to see if szL2 is larger than szL1
if (szL2 <= szL1)
{
cout << "Error. sizeL2 must be larger than sizeL1. Please try again." << endl << endl;
return 0;
}
//Read file contents*****
while (cin >> info) //check this part
{
//If it is a 1, increment read files
if (info == 1)
{
cin >> rd_add[i++];
rds++;
}
else if (info == 0)
{
cin >> wrt_add[j++];
wrt++;
}
else
{
continue;
}
}
total = rds + wrt;
//Print the arguments read
cout << endl << "Input Parameters read:" << endl;
cout << "SizeL1: " << szL1 << endl;
cout << "SizeL2: " << szL2 << endl;
cout << "Type: " << type << endl;
//Print file stats
cout << endl << "Memory References Read from File" << endl;
cout << "Total: " << total << endl;
cout << rds << " Reads" << endl;
cout << wrt << " Writes" << endl;
return 0;
}
If you want to get only the hexadecimal values in a vector and your file is as you said you can just do it as below:
String hexValue, dummy;
Vector<String> hexValueVector;
ifstream fin("big_trace.txt");//open big trace file********
if (fin.is_open()){
cout << "File opened successfully" << endl;
while (!fin.eof()){
fin >> dummy >> hexValue;
hexValueVector.push_back(hexValue);
....//your remaining code
Do not forget to include the Vector library.
#include <vector>
Hope this will help you.
EDITED:
if you need the dummy too you have just to put both values in a structure:
struct myStructure{
String dummy;
String hexValue;
};
and instead of creating a vector of string you create a vector of myStructure:
Vector<myStructure> myStructureVector;
to fill your vector you have just to do this:
myStructure myStructure;
if(fin.is_open()){
...
while (!fin.eof()){
fin >> myStructure.dummy >> myStructure.hexValue;
myStructureVector.push_back(myStructure);
If this solves your problem, please vote for the answer.
About Vector, it is a STL container, if you want more details about it check http://www.cplusplus.com/reference/vector/vector/