program crashes

hi, this code will compile but when i run it it crash on me..I have found the prolem but i can't seem to fix it. its on strcpy that i'm getting the problem.. How do i fix it so that it will stop crashing. I get a return value of 255 when it crashes

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

int main(int argc, char** argv) {
	
string wordoftheday;
vector<string> first_word_of_the_day;
srand(time(NULL));
int random = rand() % ( 30);  
ifstream word_of_the_day("word_of_the_day.txt");	
while (getline(word_of_the_day, wordoftheday))


{

   first_word_of_the_day.push_back(wordoftheday);
}
	char wordotd[100];
 		strcpy (wordotd,first_word_of_the_day[random].c_str());  //the prolem is right here, program crash on this line
cout <<wordotd<<endl;
	return 0;
}

strcpy relies on you making sure that the target memory is correct, the source memory is correct, and that you don't write so much that you overrun the target memory.

So don't.

Use proper C++ strings instead.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <cstdlib>
#include <ctime>

int main()
{
    std::ifstream word_file( "word_of_the_day.txt" );

    if( word_file.is_open() )
    {
        std::vector<std::string> words_of_the_day;
        std::string line ;
        while( std::getline( word_file, line ) ) words_of_the_day.push_back(line) ;

        if( !words_of_the_day.empty() )
        {
            // choose a random position in the vector.
            // consider using facilities in <random> http://en.cppreference.com/w/cpp/numeric/random
            std::srand( std::time(nullptr) );
            const std::size_t rand_pos = std::rand() % words_of_the_day.size() ;

            std::cout << words_of_the_day[rand_pos] << '\n' ; 
        }
    }
}
thanks that solved my problem.
Topic archived. No new replies allowed.