Argument - command prompts c++ - c++

So I'm trying to finish a part of a program where I have to find the last n-1 words in a vector string and shift the next word in source into the end of the vector string. Here I'm trying to write the function for 'findAndShift' and use arguments from another program to use it.
This is my part of the program.
void findAndShift(vector<string>& ngram, string source[],int sourceLength) {
if (argc == 2)///default command prompt...not declared?
{
ifstream infile;
infile.open(argv[1], ios::in);
if (infile.fail())
{
cout << argv[0] << ": "<< argv[i] << "I'm afraid I can't let you do that, Dave." << endl;
}
else
{
//get length of n
infile.seekg(0, ios::end);
const int sourceLength = infile.tellg();
int n = 0;
string word;
ngram = rand() % sourceLength;
while (!infile.eof())
{
infile >> source;
++n;
if(counter == ngram);
word = n;
}
}
}
return;
}
Here's the program I have to use for mine.
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);
} }
Any ideas?

you have to pass more argument in your program argc and argv[] as argc is just a parameter for main function and hence is not visible in other function.
Here is your modified code.
void findAndShift(vector<string>& ngram, string source[],int sourceLength, int argc, char argv[0], argv[1],argv[i]){
if (argc == 2)///default command prompt...not declared?
{
ifstream infile;
infile.open(argv[1], ios::in);
if (infile.fail())
{
cout << argv[0] << ": "<< argv[i] << "I'm afraid I can't let you do that, Dave." << endl;
}
else
{
//get length of n
infile.seekg(0, ios::end);
const int sourceLength = infile.tellg();
int n = 0;
string word;
ngram = rand() % sourceLength;
while (!infile.eof())
{
infile >> source;
++n;
if(counter == ngram);
word = n;
}
}
}
return;
}
your main code
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, argc,argv[0],argv[1],argv[i]);
} }
I haven''t tested it.
If it still not work try to use char * in argument list of findAndShift
Hope it helps....

Related

Dictionary with pointers

I want to write a program that adds words to a lexicon with pointers. However, I must not use strdup(), how can I do that? Below is what I tried but it gives me this error:
Exception thrown at 0x7C87EE72 (ucrtbased.dll) in (name of the file.exe): 0xC0000005: Access violation writing location 0xCDCDCDCD.
The problem is in the newStr() function.
#include <cstring>
#include <string>
#pragma warning (disable:4996)
#include <iostream>
using namespace std;
void delStr(char**&, int&, char*);
void newStr(char**&, int&, char*);
void printchar(char**, int, char);
char* searchStr(char**&, int&, char*);
void printAll(char**&, int);
enum ACTIONS { NEW, DELETE, SEARCH, PRINTLETTER, PRINTALL, EXIT };
int main() {
char** lexicon = NULL;//pointer to pointer fo the dictionary
int x = 0;
int size = 0;
char word[81];
char ch;
cout << "Enter 0-5:" << endl;
cin >> x;
while (x < 0 || x > 5) {//while loop for correct input
cout << "ERROR" << endl;
cin >> x;
}
while (x >= 0 && x <= 5) {
switch (x) {
case NEW:
cout << "Enter the word:" << endl;
ch = cin.get();
cin.getline(word, 80);
newStr(lexicon, size, word);
printAll(lexicon, size);
break;
case DELETE:
cout << "Enter the word to delete:" << endl;
ch = cin.get();
cin.getline(word, 80);
delStr(lexicon, size, word);
printAll(lexicon, size);
cout << endl;
break;
case SEARCH:
cout << "Enter the word to search for:" << endl;
ch = cin.get();
cin.getline(word, 80);
searchStr(lexicon, size, word);
break;
case PRINTLETTER:
cout << "Enter the char:" << endl;
ch = cin.get();
ch = cin.get();
printchar(lexicon, size, ch);
cout << endl;
break;
case PRINTALL:
if (size > 0 && lexicon != NULL) {
printAll(lexicon, size);
}
break;
case EXIT:
return 0;
break;
}
cout << "Enter your choice:" << endl;
cin >> x;
while (x < 0 || x > 5) {//while loop for correct input
cout << "ERROR" << endl;
cin >> x;
}
}
return 0;
}
void printAll(char**& lex, int size) {
for (int i = 0; i < size; i++) {
cout << lex[i] << " ";
}
cout << endl;
}
void newStr(char**& lex, int& size, char* word) {
int i = 0;
for (i = 0; i < size; i++) {
if (strcmp(lex[i], word) == 0) {
//cout << "Word " << word << " already exists\n";
return;
}
}
if (size == 0) {
lex = new char* [1];
for (int i = 0; i < strlen(word); i++) {
strcpy(*lex, word);
}
size++;
}
else {
char** temp = new char* [size + 1];
for (i = 0; i < size; i++) {
temp[i] = lex[i];
}
//strcpy(temp[size],word);
strcpy(temp[size], word);
delete[] lex;
lex = temp;
size++;
}
}
void delStr(char**& lex, int& size, char* word) {
int j = 0;
for (int i = 0; i < size; i++) {
if (strcmp(lex[i], word) == 0) {
for (j = i; j < size - 1; j++) {
lex[j] = lex[j + 1];
}
size--;
char** temp = new char* [size];
for (j = 0; j < size; j++) {
temp[j] = lex[j];
}
delete[] lex;
lex = temp;
}
}
}
void printchar(char** lex, int size, char ch) {
for (int i = 0; i < size; i++) {
if (lex[i][0] == ch) {
cout << lex[i] << " ";
}
}
}
char* searchStr(char**& lex, int& size, char* word) {
for (int i = 0; i < size; i++) {
if (strcmp(lex[i], word) == 0) {
cout << "Found" << endl;
//cout << "Word " << word << " already exists\n";
return lex[i];
}
}
cout << "Not found";
return NULL;
}

Where to delete the dynamic memory "char p"?

This is a hangman game program. I am declaring a char*p in the main which I can't understand why I am unable to delete later in the program when I don't need it. I tried it deleting later but it gives a heap memory error.
Also, I am a newbie in c++ - actually in programming - I will also appreciate if you can help me on how can I make the output of this program(on console) look more attractive and interactive. Like where should I use system("cls") commands more that can make it look more readable and remove non-essential information. Make a file in the same directory of the program with name either easy,medium or hard. so that it can have input from it when u run the program..
#pragma once
#include<iostream>
#include<string>
#include<ctime>
#include <cstdlib>
#include <stdlib.h>
#include <Windows.h>
#include<fstream>
#include<ctime>
#include <chrono> // for measuring time
using namespace std;
using namespace chrono;
//scoring the game with recard to time....
// filing : user name unique id and all that
//storing the name of user , his score, long story short, make a record of every user who passes by
int len = 0, letterCount = 0, size = 0, guesses = 6;
class tstamp
{
time_point<system_clock>tstart;
time_point<system_clock>tstop;
public:
void start()
{
tstart = system_clock::now();
}
void stop()
{
tstop = system_clock::now();
}
long long elasped()
{
return duration_cast<chrono::seconds>(tstop - tstart).count();
}
};
int checkWin(string a, char *p)
{
int count = 0;
int i = 0;
char *an = new char[a.length()];
string word = p;
for (i = 0; i < a.length(); i++)
{
if (a[i] == word[i])
count++;
}
if (count == i)
return 1; // 1 means the array is equal to the string == win
else
return 0; // not win
delete[]an; // using delete here for 1st
}
void resetData(string nameOfPlayer)
{
ofstream fout;
fout.open(nameOfPlayer + ".txt", ios::trunc);
//fout << "No Record";
fout.close();
}
void playerDetails(string nameOfPlayer, string a, bool status, float timeTaken)
{
char check = '\0';
ofstream fout;
fout.open(nameOfPlayer + ".txt", ios::app);
if (status == true)
fout << "Status : WON" << endl;
else
fout << "Status : LOST" << endl;
fout << "Word : " << a << endl;
fout << "Time taken to guess : " << timeTaken << " seconds" << endl;
fout << "********************************************";
fout << endl << endl;
fout.close();
}
string * grow(string *p, string temp) // to regrow the string array!!!!!
{
string* newArray = new string[size + 1];
for (int i = 0; i<size - 1; i++)
{
*(newArray + i) = *(p + i);
}
newArray[size - 1] = temp;
delete[] p;
return newArray;
}
char inGameMenu(char reset)
{
reset = '\0';
cout << "\n\t--->To reset your record press 'r' : ";
cout << "\n\n\t--->To display your previous record press 'd' : ";
cout << "\n\n\t--->To continue press 'x' : ";
cout << "\n\n\t--->To Exit the game press 'q' : ";
cout << endl << "\n\n\t--->Your Choice : ";
cin >> reset;
return reset;
}
string provideWord(string *contents, string a)
{
srand(time(NULL));
int i = rand() % size;
a = contents[i];
return a;
}
string* read(string fileName, string contents[])
{
string ext = ".txt";
fileName = fileName + ext;
fstream fin;
fin.open(fileName);
if (fin.is_open())
{
fin >> contents[0];
size++;
string temp;
while (fin >> temp)
{
size++;
contents = grow(contents, temp);
}
}
else
cout << "\n\tFile Not Found\n\n\n";
return contents;
}
char * makeAsterisks(string temp) // this will make astericks of the word player have to guess.
{
int len = temp.length();
char*p = new char[len];
for (int i = 0; i < len; i++)
{
p[i] = '-';
}
p[len] = '\0';
return p;
}
void displayRecord(string fileName, string display)
{
fstream fout;
fout.open(fileName + ".txt");
cout << "\n----------------------------------------------------------------------------------------------------------------";
if (fout.is_open())
{
cout << endl << endl;
while (getline(fout, display))
cout << display << endl;
}
else
cout << "\n!!No Record Found!!\nYou might be a new user\n";
cout << "\n----------------------------------------------------------------------------------------------------------------\n";
fout.close();
}
char * checkMyGuess(string word, char userGuess, char ar[])
{
bool flag = true;
for (int i = 0; i < word.length(); i++)
{
if (userGuess == word[i])
{
flag = false;
ar[i] = userGuess;
letterCount++;
}
}
if (flag == true)
{
_beep(450, 100);
cout << "\n\t!!!Wrong!!!\n";
len--;
guesses--;
}
return ar;
}
void rules()
{
system("Color 09 "); // for color effects
cout << "\n\n\t\t\t=====================\n";
cout << "\t\t\t||\tHANGMAN\t ||\n\t\t\t||\tRules\t ||"
<< "\n " << "\t\t\t=====================\n\n\n";
_beep(4000, 500);
system("Color 08 "); // for color effects
system("Color 07 "); // for color effects
cout << "\t--> Computer will think of a word and you have try\n" // rules
<< "\t to guess what it is one letter at a\n"
<< "\t time. Computer will draw a number of dashes \n "
<< "\tequivalent to the number of letters in the word.\n "
<< "\t If you suggest a letter that occurs\n "
<< "\t in the word, the computer will fill in the blank(s)\n"
<< "\t with that letter in the right place(s).\n"
<< "\t The session will be timed. \n\n";
cout << endl;
cout << "\t--> Total number of wrong choices : 6\n\n"; //wrong turns
cout << "\t--> Objective : Guess the word / phrase before you run out of choices!\n\n"; // obj
}
int checkForName(string fileName)
{
fileName = fileName + ".txt";
char line = '\0';
fstream fin;
char fromFile[7] = "\t\tName";
fin.open(fileName);
int i = 0,
check = 0;
while (fin.get(line) && i < 7)
{
if (line == fromFile[i++])
check++;
}
if (check == i - 1)
return 1;
else
return 0;
fin.close();
}
void checkForRecord(string fileName)
{
fileName = fileName + ".txt";
char line = '\0';
fstream fin;
char fromFile[7] = "No";
fin.open(fileName);
int i = 0,
check = 0;
while (fin.get(line) && i < 3)
{
if (line == fromFile[i++])
check++;
}
if (check == i - 1)
{
fin.open(fileName, ios::trunc);
fin.close();
}
fin.close();
}
int menu(int mode) // this function asks the user to enter the difficulty level of the game!!! You can't even beat medium!
{
system("cls");
cout << "Please select the Level of Game :\n";
cout << "1. Easy" << endl;
cout << "2. Medium" << endl;
cout << "3. Hard" << endl << endl;
cout << "Your Choice : ";
cin >> mode;
while (!(mode <= 3 && mode >= 1))
{
cout << endl << endl;
cout << "Please Enter the number of given choices: ";
cin >> mode;
}
return mode;
}
int comMenu(string nameOfPlayer, char reset)
{
string readData;
reset = '\0';
while (1)
{
reset = inGameMenu(reset);
if (reset == 'r')
{
resetData(nameOfPlayer);
system("cls");
Sleep(1);
}
else if (reset == 'd')
{
system("cls");
Sleep(1); // just to add a little delay!
cout << "Your Record Shows :--->\n";
displayRecord(nameOfPlayer, readData);
}
else if (reset == 'x')
break;
else if (reset == 'q')
break;
else
{
cout << "\n\n!!!Invalid Choice!!!\n\n";
}
}
return reset;
}
int main()
{
string nameOfPlayer;
char anyKey = '\0';
string name;
cout << endl;
rules();
cout << "Enter the name of player: ";
cin >> nameOfPlayer;
while (1)
{
char reset = '\0';
reset = comMenu(nameOfPlayer, reset);
if (reset != 'q') // check to exit the game
{
int uniquevar = checkForName(nameOfPlayer);
if (uniquevar != 1)
{
ofstream fout;
fout.open(nameOfPlayer + ".txt", ios::app);
fout << "\t\tName of Player : " << nameOfPlayer << endl << endl << endl;
fout.close();
}
while (1)
{
system("Color E0");
bool status = true; //initially win
size = 0,
len = 0,
letterCount = 0,
guesses = 6;
string a = ""; // it holds the word
string *contents = new string[1];
string name = "";
char b;
int mode = 0;
tstamp ts;
bool notRepeat[26] = { 0 };
if (anyKey == 'X' || anyKey == 'x')
break;
else
{
mode = menu(mode);
if (mode == 1)
name = "easy";
else if (mode == 2)
name = "medium";
else if (mode == 3)
name = "hard";
contents = read(name, contents);
cout << endl;
}
a = provideWord(contents, a);
delete[]contents;
len = a.length();
char *p = makeAsterisks(a); // detele it later
cout << "Total number of words to guesses: " << len << endl << endl;
cout << "Total guesses you have: 6\n";
cout << "Word :\n\n\t" << p << endl << endl;
ts.start(); // it starts counting the time...
while (guesses != 0)
{
cout << "Enter char: ";
cin >> b;
if (b >= '1' && b <= '9')
{
cout << "\n\nThere is not number in the given word\n\n";
continue;
}
int temp = b - 97; // it assigns the value of alphabet to temp i.e a=0,b=0 so on...
if (notRepeat[temp] != false)
{
cout << "\n\nYou've already used this word\n\n";
cout << "Remaining Choices: " << guesses << endl << endl;
continue;
}
else
{
p = checkMyGuess(a, b, p);
int checkingTheWin = checkWin(a, p);
if (checkingTheWin == 0)
{
}
else
{
cout << "\n\n\t*************You Won****************\n\n";
status = true; //true = win
break;
}
notRepeat[temp] = true;
cout << endl << endl;
cout << "Remaining Choices: " << guesses << endl;
cout << endl << '\t' << p << endl;
}
}
ts.stop();
cout << "Time Taken: " << ts.elasped() << " seconds\n\n";
p = NULL;
if (guesses == 0)
{
status = false; //false = lose
checkForRecord(nameOfPlayer);
playerDetails(nameOfPlayer, a, status, time); // right here it will create a file with the name of user
cout << "\n\nGame Over!!!\n\n";
cout << "\t\tThe word was \n\t\t\" " << a << "\"\n\n";
}
else
{
checkForRecord(nameOfPlayer);
playerDetails(nameOfPlayer, a, status, time); // right here it will create a file with the name of user
}
break;
} //ending block of while(1) first
system("color 07"); // shashka!!
}
if (reset == 'q') // to exit the game if the user decides so right away!!
break;
}
cout << "Exiting the Game\n\n";
_beep(3000, 500); // ending sound!
return 0;
}
In makeAsterisks you don't allow for the null terminator. You need to allocate one more character
char * makeAsterisks(string temp)
{
int len = temp.length();
char*p = new char[len + 1]; // <-- change here
for (int i = 0; i < len; i++)
{
p[i] = '-';
}
p[len] = '\0';
return p;
}
Now having said that, you are already using string, why not make life easier for yourself and use it everywhere? Here's makeAsterisks rewritten to use string.
string makeAsterisks(string temp)
{
return string(temp.length(), '-');
}

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;
}

Why do I always return position 10 in my code?

In my program for sorting an array of strings, I always get a position of 10 when binary searching a name. Why does this occur?
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
const int MAXNAMES = 20;
void readArray(string names[])
{
ifstream inFile("names.txt");
string line;
int counter = 0;
if (!inFile.is_open())
{
cout << endl << "Cannot locate file names.txt" << endl;
exit(0);
}
else
{
cout << "Succesfully opened \"names.txt\" file." << endl;
}
while (getline(inFile, line))
{
names[counter++] = line;
}
inFile.close();
}
void displayArray(string names[])
{
for (int i = 0; i < MAXNAMES; i++)
{
cout << names[i] << endl;
}
cout << endl;
}
void selectionSort(string names[])
{
int i, j, minIndex;
string minString;
for (i = 0; i < MAXNAMES - 1; i++)
{
minIndex = i;
minString = names[i];
for (j = i + 1; j < MAXNAMES; j++)
{
if (minString.compare(names[j]) > 0)
{
minString = names[j];
minIndex = j;
}
}
if (minIndex != i)
{
string temp = names[i];
names[i] = names[minIndex];
names[minIndex] = temp;
}
}
}
void sequentialSearch(string names[], string name)
{
bool found = false;
int index = 0;
for (int i = 0; i < MAXNAMES; i++)
{
if (name.compare(names[i]) == 0)
{
found = true;
index = i;
break;
}
}
if (!found)
cout << "The name is not found." << endl;
else
cout << endl << "The name is found at index: " << index + 1 << "." << endl;
}
void bubbleSort(string names[])
{
string temp;
for (int j = 0; j < MAXNAMES - 1; j++)
{
for (int i = j + 1; i < MAXNAMES; i++)
{
if (names[j].compare(names[i]) > 0)
{
temp = names[j];
names[j] = names[i];
names[i] = temp;
}
}
}
}
int binarySearch(string names[], string name)
{
int l = 0;
int r = MAXNAMES - 1;
while (l <= r)
{
int m = l + (r - l) / 2;
int res = 0;
if (name == names[m])
res = 0;
if (res == 0)
return m;
if (name > (names[m]))
l = m + 1;
else
r = m - 1;
}
return -1;
}
int main()
{
string names[MAXNAMES];
readArray(names);
cout << "Array before sort:" << endl << endl;
displayArray(names);
cout << "Array after selection sort is:" << endl << endl;
selectionSort(names);
displayArray(names);
string nameToSearch;
cout << "Enter a name to (sequential) search for: ";
std::getline(std::cin, nameToSearch);
sequentialSearch(names, nameToSearch);
string choice;
cout << endl << "Replace first element of the array \"" << names[0] << "\" with \"" << nameToSearch << "\" Yes or No: ";
std::getline(std::cin, choice);
if (choice.compare("Yes") == 0 || choice.compare("yes") == 0)
{
names[0] = nameToSearch;
}
bubbleSort(names);
cout << endl << "Array after Bubble Sort is:" << endl;
displayArray(names);
cout << "Enter a name to (binary) search for: ";
std::getline(std::cin, nameToSearch);
int index = binarySearch(names, nameToSearch);
if (index == -1)
cout << endl << "The name is not found." << endl;
else
cout << endl << "The name is found at position " << (index + 1) << endl;
return 0;
}
Here is the input file used for the code:
names.txt
Collins, Bill
Smith, Bart
Allen, Jim
Griffin, Jim
Stamey, Marty
Rose, Geri
Taylor, Terri
Johnson, Jill
Allison, Jeff
Looney, Joe
Wolfe, Bill
James, Jean
Weaver, Jim
Pore, Rob
Rutherford, Rose
Javens, Renee
Harison, Rose
Setzer, Cathy
Pike, Gordon
Holland, Beth
In binarySearch, you have this sequence:
int res = 0;
if (name == names[m])
res = 0;
if (res == 0)
return m;
Since res will always be zero when that 2nd if is reached, it will always return on the first time thru the loop.
You can remove res completely, and just replace all that with
if (name == names[m])
return m;

read text file then add character to list?

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.