Recursive Palidromes - c++

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;

Related

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

How to deal with space input comparing word inverse C++

We are taking user input and reversing it in the background and asking the user what is the reverse. Then we compare realreverse and userreverse and say that it's correct or how many mistakes were made. Also we are counting sentences with using dots, and the user should end his input with #.
For example:
hi. how are you doing. #
or
hi bro how are u.
im good. #
The problem is my program is only working if the input doesn't contain any spaces.
hihowareyoudoing. thanksimfinebro #
If the input is like that, it's working.
it works
hihowareyoudoing.
thanksimfinebro. #
This 2 column also working
code:
(program shows correct inverse for testing)
#include <iostream>
#include <string>
using namespace std;
void Comparison(string reverseReal, string reverseUser) {
int wrongCount = 0;
if (reverseReal.length() != reverseUser.length()) {
cout << "These strings are not comparable." << endl;
}
else {
for (int i = 0; i < reverseReal.length(); i++) {
if (reverseReal.substr(i, 1) != reverseUser.substr(i, 1)) {
wrongCount++;
}
}
cout << "Number of mistakes: " << wrongCount << endl;
if (wrongCount == 0){
cout << "gj correct reverse" << endl;
}
}
}
string getReverse(string sentence) {
string reverseResult = "";
for (int i = sentence.length() - 1; i >= 0; i--) {
reverseResult += sentence.substr(i, 1);
}
return reverseResult;
}
int findsnumber(string snumber)
{
unsigned int sentences = 0, index = 0, length;
string searchPattern = ".";
length = snumber.length();
while (index < length)
{
index = snumber.find(searchPattern, index);
if (index != string::npos)
{
index += searchPattern.length();
sentences++;
}
}
return sentences;
}
// Gets the string until it finds a dot in it
string getOneSentence(string sentence) {
while (sentence.find(".") != string::npos) {
int dotFinder = 0;
string sub = "";
dotFinder = sentence.find(".");
sub = sentence.substr(0, dotFinder);
return sub;
}
return "";
}
int main() {
string input = "";
string result = "";
string reverseReal = "";
int i = 1;
cout << "Welcome to my cancer c++ programme." << endl;
cout << "Enter the paragraph with # at the end to end it:" << endl;
while (cin >> input && input != "#") {
result += input + " ";
}
int sentnumber = findsnumber(result);
cout << "Number of sentences in the given string " << sentnumber << endl;
while (result.find(".") != string::npos) {
string sub = "";
string subReverse = "";
string reverse = "";
string reverseson = "";
cout << i << "/" << sentnumber << endl;
sub = getOneSentence(result);
subReverse = getReverse(sub);
cout << "reverse of the sub " << subReverse << endl;
cout << "Sentence " << i << " : " << sub << endl;
cout << "Enter the reverse of your sentence" << endl;
while (cin >> reverse && reverse != "#"){
reverseson += reverse + "";
}
Comparison(subReverse, reverseson);
result = result.substr(result.find(".") + 2, result.length());
i++;
}
cin.ignore();
cin.get();
}
cin does not support input string with spaces. So, to input a string containing spaces you need to use getline()The correct syntax is std::getline(std::cin, input);
Edited Your Code!
#include <iostream>
#include <string>
using namespace std;
void Comparison(string reverseReal, string reverseUser) {
int wrongCount = 0;
if (reverseReal.length() != reverseUser.length()) {
cout << "These strings are not comparable." << endl;
}
else {
for (int i = 0; i < reverseReal.length(); i++) {
if (reverseReal.substr(i, 1) != reverseUser.substr(i, 1)) {
wrongCount++;
}
}
cout << "Number of mistakes: " << wrongCount << endl;
if (wrongCount == 0){
cout << "gj correct reverse" << endl;
}
}
}
string getReverse(string sentence) {
string reverseResult = "";
for (int i = sentence.length() - 1; i >= 0; i--) {
reverseResult += sentence.substr(i, 1);
}
return reverseResult;
}
int findsnumber(string snumber)
{
unsigned int sentences = 0, index = 0, length;
string searchPattern = ".";
length = snumber.length();
while (index < length)
{
index = snumber.find(searchPattern, index);
if (index != string::npos)
{
index += searchPattern.length();
sentences++;
}
}
return sentences;
}
// Gets the string until it finds a dot in it
string getOneSentence(string sentence) {
while (sentence.find(".") != string::npos) {
int dotFinder = 0;
string sub = "";
dotFinder = sentence.find(".");
sub = sentence.substr(0, dotFinder);
return sub;
}
return "";
}
int main() {
//char input = '\0';
string input = "";
string result = "";
string reverseReal = "";
int i = 1;
cout << "Welcome to my cancer c++ programme." << endl;
cout << "Enter the paragraph with # at the end to end it:" << endl;
getline(cin, input,'#');
result = input;
int sentnumber = findsnumber(result);
cin.clear();
cout << "Number of sentences in the given string " << sentnumber << endl;
while (result.find(".") != string::npos) {
string sub = "";
string subReverse = "";
string reverse = "";
string reverseson = "";
cout << i << "/" << sentnumber << endl;
sub = getOneSentence(result);
subReverse = getReverse(sub);
cout << "reverse of the sub " << subReverse << endl;
cout << "Sentence " << i << " : " << sub << endl;
cout << "Enter the reverse of your sentence" << endl;
cin.clear();
cin.ignore();
getline(cin,reverse,'#');
reverse.erase(reverse.end() - 1, reverse.end());
reverseson = reverse;
Comparison(subReverse, reverseson);
result = result.substr(result.find(".") + 2, result.length());
i++;
}
system("pause");
}

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++)

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.

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....