Where to delete the dynamic memory "char p"? - c++

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(), '-');
}

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

Counter adding items to array with remainder

I am creating an RPG shop. It must have items, gold, and item price. Essentially creating an inventory. What i am trying to accomplish is, where the players gold is 0 they cannot add any more items to their inventory, and cannot have negative gold.
When running my code in debug mode it appears to be doing what i want, but when the function exits the amount the player requested has not been countered.
Keep in mind i am still new to c++.
Thanks
#include <iostream>
#include <string>
using namespace std;
// Global consts
const int numItems = 4;
const string items[numItems] = {"boots", "hats", "cats", "bats"}; // create string array of numItems items.
// Create stuct, that holds:
// Item, gold, price.
struct Inv {
int pInv[numItems] = {0, 0, 0, 0};
int gold = 100;
int itemPrice[numItems] = { 10, 6, 12, 15 };
}inv;
void iniItems();
void printItems();
bool buyItems();
bool sellItems();
int main() {
bool isDone = false;
iniItems();
while (isDone == false) {
printItems();
int choice;
bool x = false;
cout << "\nWhat would you like to do? Enter (" << 1 << "-" << 2 << "): " << endl;
cout << "1: Buy Items. \n2: Sell Items." << endl; cin >> choice; cout << endl;
while (x == false) {
if (choice == 1) {
x = buyItems();
}
if (choice == 2) {
x = sellItems();
}
}
}
system("pause");
// dynamic memory not implemented yet. Must wait for working fix of shoppe.cpp
}
void iniItems() {
cout << "** Shop Inventory: **" << endl;
for (int i = 0; i < numItems; i++) {
cout << i + 1 << " - " << items[i] << " - price: $" << inv.itemPrice[i] << endl;
}
}
void printItems() {
cout << "\n** Player Inventory: **" << endl;
cout << "Gold: $" << inv.gold << endl;
for (int i = 0; i < numItems; i++) {
cout << inv.pInv[i] << " x " << items[i] << endl;
}
}
bool buyItems() {
bool exit = false;
int amount;
const int remainder = 10;
printItems();
cout << "\nEnter -1 to quit." << endl;
cout << "What would you like to buy? Enter (" << 1 << "-" << 4 << "): " << endl;
// Get item info.
while (exit == false) {
int inp;
cout << "Item: "; cin >> inp; cout << endl;
cout << "Amount: "; cin >> amount; cout << endl;
// Check if input is valid.
if (inp > 0 && inp <= numItems) {
if (amount >= 0) {
inv.pInv[inp - 1] = 1 * amount;
inv.gold = inv.itemPrice[inp - 1] / amount;
}
// If gold is 0, make sure the user cannot gain more items.
if (inv.gold <= 0) {
int tmp;
inv.gold = 0;
tmp = remainder - amount;
for (int i = tmp; i >= 0; i++) {
inv.pInv[inp - 1]--;
}
return inv.pInv[inp - 1];
}
if (inp == -1) {
return true;
}
if (inp > numItems) {
cout << "Enter valid number." << endl;
return false;
}
else return false;
}
}
if (exit == true) {
return true;
}
}
So i limited the code down into a do while loop with a counter for the gold, in the buyItems() function.
Here it is, if anyone is interested.
do {
inv.gold -= inv.itemPrice[inp - 1];
++(inv.pInv[inp - 1]);
} while (inv.gold > 0);
if (inv.gold < 0) {
inv.gold = 0;
inv.pInv[inp - 1]--;
}
printItems();

Recursive Palidromes

I am attempting to write a recursive function for palidromes. I get a correct answer when I test the string when no command arguments are inputted. When when there is a command argument. It keeps returning false even thought its true. What did I do wrong.
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
bool palindrome(string word);
string formatString(string s);
int main(int argc , char * argv[])
{
if(argc < 2)
{
string inputString;
int last = inputString.length()-1;
cout << "Welcome To My Palidrome Tester!" << endl;
cout << "Please Enter A String To Test if it is A Palidrome: ";
getline(cin, inputString);
//testForPalindrome(inputString);
string newW = formatString(inputString);
//cout << "It is a palindrome" ? (palindrome(newW) == true) : "It is Not a palidrome";
if(palindrome(newW) == true)
cout << "It is a palindrome" << endl;
else
cout << "It is not palindrome" << endl;
}
else
{
string commandStr;
for(int i = 1; i < argc; i++)
{
commandStr += argv[i];
}
string newW = formatString(commandStr);
if(palindrome(newW) == true)
cout << "It is a palindrome" << endl;
else
cout << "It is not palindrome" << endl;
}
return 0;
}
bool palindrome(string word)
{
int length = word.length();
string first = word.substr(0,1);
string last = word.substr((length - 1), 1);
if (first == last)
{
word = word.substr((0 + 1), (length - 2));
if (word.length() <= 1) return true; // Problem line?
palindrome(word);
}
else
return false;
}
string formatString(string s)
{
string p;
size_t position = s.find(' ', 0);
while(position != string::npos)
{
s.erase(position,1);
size_t newPosition = position+1;
position = s.find(' ', newPosition);
}
for(int i = 0; i < s.size(); i++)
{
if(ispunct(s[i]))
{
s.erase(i,1);
}
if(isupper(s[i]))
{
s = tolower(s[i]);
}
}
return s;
}
string inputString;
int last = inputString.length()-1;
You are taking string's length too soon. Change to
string inputString;
cout << "Please Enter A String To Test if it is A Palidrome: ";
getline(cin, inputString);
formatString(inputString);
int last = inputString.length() - 1;
if (recursionPalindrome(inputString, 0, last) != 0)
cout << "It is a Palindrome" << endl;
else
cout << "It is not a palindrome" << endl;
It seems return false with print "Palindrome", while it should be "not a palindrome" from recursionPalindrome logic ?
if(recursionPalindrome(inputString,0,last) == 0)
cout << "It is a Palindrome" << endl;
else
cout << "It is not a palindrome" << endl;

I keep getting subscript out of range don't know how to fix it [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
#include <iostream>
#include <fstream>
#include <string>
#include <ctime>
#include <cstdlib>
using namespace std;
const int MAX_NUMS = 200; // Constant for the maximum number of words.
const int MAX_GUESSES = 8;
const string LETTERS = "abcdefghijklmnopqrstuvwxyz";
char inputLetter();
int findChar(char letter, string&word);
string getGuessedWord(string&secretWord, string&lettersGuessed);
string getLettersGuessed(char letter, string&lettersGuessed, int n);
void display(string&lettersGuessed, string&wordGuessed, int num, int pos);
bool isDone(string wordGuessed);
int main()
{
string oneWord; // holds one word from input file
string secretWord; // holds secret word to be guessed
string words[MAX_NUMS]; // holds list of words from input file
int randomValue; // holds index of secret word
int count = 0; // holds number of words in the file
// Declare an ifstream object named myFile and open an input file
ifstream myFile;
myFile.open("P4Words.txt");
// Exit program if cannot open file for input
if (!myFile)
{
cout << "Error: Unable to open file for input" << endl;
return 0;
}
// Input words from a file into words array
// Add your code here ...
myFile >> oneWord;
while (!myFile.eof())
{
words[count] = oneWord;
count++;
myFile >> oneWord;
}
myFile.close();
cout << count << " words loaded." << endl;
srand(static_cast<unsigned int>(time(0)));
// Select a secret word
// Add your code here ...
secretWord = words[rand() % (count + 1) ];
// Possible useful variables the loop
string lettersGuessed = ""; // holds letters guessed so far
string wordGuessed; // holds current word guessed like �_ pp_ e�
int incorrectGuesses = 0; // holds number of incorrect guesses so far
char letter; // holds a guessed letter
bool done = false; // have not guessed the word yet
int num = 8; int pos;
cout << "Welcome to the game, Hangman V1 by Your Name!" << endl;
cout << "I am thinking of a word that is " << secretWord.length()
<< " letters long." << endl;
// Set up a loop to input guesses and process
// Add your code here ...
do
{
letter = inputLetter();
pos = findChar(letter, secretWord);
wordGuessed = letter;
lettersGuessed = getLettersGuessed(letter, lettersGuessed, 8 - num);
wordGuessed = getGuessedWord(secretWord, lettersGuessed);
display(lettersGuessed, wordGuessed, num, pos);
done = isDone(wordGuessed);
num--;
} while ((num > 1) && (done == false));
// Check for won or lost
// Add your code here ...
if (done == false)
{
cout << "sorry you lose..." << endl;
}
if (done == true)
{
cout << "congratulations! " << endl;
}
system("pause"); // stop program from closing, Windows OS only
return 0;
}
// Add function definitions here ...
char inputLetter()
{
int i;
char letter;
do
{
cout << "please guess a letter: " << endl;
cin >> letter;
for (i = 0; i < 25; i++)
{
if (letter == LETTERS[i])
{
return letter;
}
}
if (letter != LETTERS[i])
{
cout << "Oops! That is an invalid character." << endl;
}
} while (letter != LETTERS[i]);
}
int findChar(char letter, string &word)
{
int i = 0; int pos = 0; bool found = false;
do
{
if (word[pos] == letter)
{
return pos;
found = true;
}
pos++;
} while (pos<word.length() - 1);
if (found == false)
{
return -1;
}
}
string getGuessedWord(string&secretWord, string&letterGuessed)
{
string temp;
temp = secretWord;
for (size_t k = 0; k <= temp.length() - 1; k++)
{
temp[k] = '_';
}
for (size_t i = 0; i <= temp.length() - 1; i++)
{
for (size_t j = 0; j <= temp.length() - 1; j++)
{
if (letterGuessed[i] == secretWord[j])
{
temp[j] = letterGuessed[i];
}
}
}
return temp;
}
string getLettersGuessed(char letter, string&lettersGuessed, int n)
{
string temp;
temp = letter;
lettersGuessed.insert(n, temp);
return lettersGuessed;
}
void display(string&lettersGuessed, string&wordGuessed, int num, int pos)
{
if (pos != -1)
{
cout << "You have " << num << " guesses left." << endl;
cout << "Letters guessed so far: " << lettersGuessed << endl;
cout << "Good guess!: " << wordGuessed << endl;
cout << "-----------------------------------------------------" << endl;
}
if (pos == -1)
{
cout << "You have " << num << " guesses left." << endl;
cout << "Letters guessed so far: " << lettersGuessed << endl;
cout << "Oops! that letter is not my word: " << wordGuessed << endl;
cout << "-----------------------------------------------------" << endl;
}
}
bool isDone(string wordGuessed)
{
bool done = false; int k = 0;
for (size_t i = 0; i <= wordGuessed.length() - 1; i++)
{
if (wordGuessed[i] == '_')
{
k++;
}
}
if (k == 0)
{
done = true;
}
return done;
}
it says subscript is out of range I need help to fix it
let me know how to fix it please its a project that is due very soon
that's all I got so far
Change:
for (size_t i = 0; i <= temp.length() - 1; i++)
to:
for (size_t i = 0; i <= letterGuessed.length() - 1; i++)

Argument - command prompts 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....