I've only used strings in my programs but for class I was instructed to use character arrays which I am completely unfamiliar with. Basically I need to create random sentences by pulling verbs, nouns, etc from an array of char arrays. For some reason though, if I pull the last word in the array I get gibberish. Like for example in the line return articles[rand()%5] if the random number is 4, my sentence prints random characters for the word, even though there does exist a word at array location 4. The only way I've been able to solve it is to extend the arrays to size six instead of five. Can someone explain to me why I get gibberish when I try to return the last word in the array? MSVC++ by the way.
Code:
#include<cstring>
#include<iostream>
#include<ctime>
using namespace std;
void printSentence(void);
char* returnArticle(void);
char* returnNoun(void);
char* returnVerb(void);
char* returnPreposition(void);
int main()
{
srand(time(NULL));
for (int x=0; x<20; x++)
{
printSentence();
}
return 0;
}
void printSentence()
{
// create the sentence by pulling random verbs, articles, prepositions, and nouns
char sentence[50]="";
char period[2]=".";
char space[2]=" ";
strcat(sentence, returnArticle());
strcat(sentence, space);
strcat(sentence, returnNoun());
strcat(sentence, space);
strcat(sentence, returnVerb());
strcat(sentence, space);
strcat(sentence, returnPreposition());
strcat(sentence, space);
strcat(sentence, returnArticle());
strcat(sentence, space);
strcat(sentence, returnNoun());
strcat(sentence, period);
sentence[0]=toupper(sentence[0]);
cout<<sentence<<endl;
}
char* returnArticle()
{
char articles[5][5]={"the", "a", "one", "some", "any"};
return articles[rand()%5];
}
char* returnNoun()
{
char nouns[5][5]={"boy", "girl", "dog", "town", "car"};
return nouns[rand()%5];
}
char* returnVerb()
{
char verbs[5][8]={"drove", "jumped", "ran", "walked", "skipped"};
return verbs[rand()%5];
}
char* returnPreposition()
{
char prepositions[5][6]={"to", "from", "over", "under", "on"};
return prepositions[rand()%5];
}