Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

C++ Array

Status
Not open for further replies.

drbk563

IS-IT--Management
Nov 21, 2006
194
0
0
US
Hello,

I am a c++ program beginner, I am trying to make a program that generates sentences. This program should take a word from each array and turn it into sentences using each word in the array.

As for example the output should be somehthing like this. The sentences does not need to make sense as long it takes each word and turn it into sentences.

I ran the program that and it does not generate correctly. Can u please help me and tell me what I need to do? THank you.

The girl jumped over.
A boy drove on.

.....







#include <iostream>
#include <ctime> //in order to use the function time();
#include <cstdlib> //contains function prototype for rand
using namespace std;


int main()
{

int index, i;
const char *article[5]={"the", "a", "one", "some", "any"};


const char *noun[5]={"boy", "girl", "dog", "town", "car"};


const char *verb[5]={"drove", "jumped", "ran", "walked", "skipped"};


const char *preposition[5]={"to", "from", "over", "under", "on"};

char sentence[100];


srand (time(0));
strcpy(sentence, "\0");
index=rand()%5;

for (i=index; i<index+10; i++)
{

strcat(sentence, article[ rand() % 5 ] );
strcat(sentence, " " );


strcat(sentence, noun[ rand() % 5 ] );
strcat(sentence, " " );


strcat(sentence, verb[ rand() % 5 ] );
strcat(sentence, " " );


strcat(sentence, preposition[ rand() % 5 ] );
strcat(sentence, " " );


strcat(sentence, "." );



}


sentence[0] = toupper(sentence[0]);



cout<<sentence<<endl;

cout<<endl;

return 0;
}
 
This is just C code plus a couple cout's. If you really want the safety & simplicity of C++, you should replace your char* arrays and strcat()'s with vectors & strings.

Also, please put code inside [ignore]
Code:
[/ignore] tags.

What exactly do you mean by "it does not generate correctly"? What does it do?
 
> for (i=index; i<index+10; i++)
index is uninitialised
Maybe for (i=0; i<10; i++)

> char sentence[100];
The longest sentence is 25 chars, and you go round 10 times.
I'm thinking buffer overflow.
A problem you wouldn't have if you used std::string.


--
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top