Re: string handling problems
It would be much easier for you if you used std::string instead of char *. Your code is currently pretty much unreadable.
Re: string handling problems
The code is very wrong and leads me to believe that you do not yet understand pointers and C++. Here are a few comments on your code and the behavior:
You do not need temp, you can use the other directly.
Code:
strcpy(temp,article[article_gen]);
strcat(sentance,temp);
strcat(sentance," ");
This will accomplish the same thing
Code:
strcat(sentance, article[article_gen]);
strcat(sentance," ");
That said, you should simply use QString and be done with it. This avoids all those pointers and messy memory copies that ultimately lead to the failure. Consider lines 37-39:
Code:
totalSentances[i]=sentance;
cout<<sentance<<endl;
*sentance=NULL;
The variable sentance is a an array of type char. In C, this also means that it is a char*. Does the value of sentance ever change? The answer is no, THE VALUE OF SENTANCE NEVER CHANGES. Remember, sentance points to an area of memory with space for 100 characters. The characters stored in those locations change, but sentance always points to the same block of memory.
If you now look at every entry in totalSentances, every entry points at the same memory location. When you print the value, the value is correct, because you just set it. The next thing that you do is set the first entry to NULL, which means that you effectively set this to an empty string.
In case you missed it, this means that every entry in totalSentances will, at the end of the loop point to the same memory location that contains an empty string.
If you had an array of type QString, however, you would assign that. I might go so far as to recommend a QStringList, and then you can replace line 37 with
Code:
totalSentances.append(sentance);
or
Code:
totalSentances << sentance;
Re: string handling problems
Can't help myself.... look at this simple example:
Code:
void randStringTest()
{
QStringList verbs; verbs <<
"drove" <<
"jumped" <<
"ran" <<
"walked" <<
"skipped" <<
"froliced" <<
"smoked";
QStringList nouns; nouns <<
"boy" <<
"girl" <<
"dog" <<
"town" <<
"car" <<
"ganja" <<
"cat";
QStringList preps; preps <<
"to" <<
"from" <<
"over" <<
"under" <<
"before" <<
"into" <<
"by";
QStringList articles; articles <<
"the" <<
"a" <<
"one" <<
"some" <<
"any";
// In c++0X, you can do this
// QStringList articles({"the","a","one","some","any"});
srand(time(0));
for (int i=0; i<20; ++i)
{
int word_gen = 0+rand()%6;
int article_gen=0+rand()%4;
sentences << articles[article_gen] + " " + nouns[word_gen] + " " + verbs[word_gen] + " " + preps[word_gen] + " " + articles[article_gen] + " " + nouns[word_gen];
qDebug(qPrintable(sentences.back()));
}
}
Result...
Quote:
the dog ran over the dog
one boy drove to one boy
a car skipped before a car
a ganja froliced into a ganja
the boy drove to the boy
some town walked under some town
the car skipped before the car