Trouble with an access violation involving strings and rand()

Hi everyone, I'm getting an access violation with a program I'm writing to generate random sentences. When I run the program, it asks me to break or continue as it shows this message:

"Unhandled exception at 0x779e15ee in Demo.exe: 0xC0000005: Access violation."

At the same time, it opens up a window with rand.c.

I'm new to programming and don't know what exactly this means or what the problem is. I reviewed the code and feel like it should be fine, especially with the rand() function. Any ideas? Thanks in advance...
dpan


#include <iostream>
using std::cin;
using std::cout;
using std::endl;

#include <cstring>

#include <ctime>

#include <cctype>

int findLast( char[] );

int main()
{
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" };
const char space[ 2 ] = { " " };
char sentence[ 100 ];

srand( time( 0 ) );

for ( int j = 0; j < 20; j++ ) {
strcat( sentence, article[ rand() % 5 ] );
strcat( sentence, space );
strcat( sentence, noun[ rand() % 5 ] );
strcat( sentence, space );
strcat( sentence, verb[ rand() % 5 ] );
strcat( sentence, space );
strcat( sentence, preposition[ rand() % 5 ] );
strcat( sentence, space );
strcat( sentence, article[ rand() % 5 ] );
strcat( sentence, space );
strcat( sentence, noun[ rand() % 5 ] );
strcat( sentence, space );
toupper( sentence[ 0 ] );
sentence[ findLast( sentence ) + 1 ] = '.';
cout << sentence << endl << endl;
}

return 0;

}

int findLast( char string[] )
{
int i;
for ( i = 0; string[ i ] != '\0'; i++ );
return i;
}
You never reset the sentence so all the loop iterations will add more and more until you run outside the array. Add sentence[0] = '\0'; to the start of the loop and I think you get what you want.
Peter87, thanks, that takes care of the access violation. Now, the next step is to figure out why the "toupper" statement isn't working. I'm trying to use one from the standard library that i've never used before...i might just write my own. I also need to figure out why I'm unable to add in the period at the end of the sentence. Thanks for your help!
toupper doesn't change what you pass in. You will have to make use of the return value.
sentence[0] = toupper(sentence[0]);


sentence[ findLast( sentence ) + 1 ] = '.';
This will add a period after the '\0'.
Why don't you use strcat to like you did for the other parts?
strcat( sentence, ".");
You do know that your findlast() is a rework of the standard strlen() call, which comes in the same set as strcpy. strcat, ... ???
Topic archived. No new replies allowed.