Getting Array from text file for strings

I have a text file (called words.txt) that contains 8 words. It goes something like this:
store
apple
tennis
etc

and I am trying to copy just one string so that the user can guess one of the array. This is basically for a Hangman project. My question is, how can I use strcpy to get one word at a time from the file? I'm thinking the code should be like this:

strcpy(words.txt, FileString)

Is this the right function to copy the string of arrays from the txt file?

I'm using the <string.h> and <stdio.h> library.
Last edited on
No, strcpy is not used to read from a file

The following will read a text file (assuming one word per line) into a vector of strings

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
vector< string > wordsVector;

fstream wordsFile;
wordsFile.open( "words.txt", ios::in );

if( wordsFile.is_open() )
{
  string s;
  while( getline( wordsFile, s ) )
     wordsVector.push_back( s );

  wordsFile.close();
}
else
  cout << "Error opening file " << errno << endl;
Hm I'm not really familiar with that language, is there a code that incorporate something like fscanf?

I had this before:

FILE *inp;
inp=fopen("words.txt", "r");
fscanf(inp, " %s", filestrings);
Here is the general code in C++. For C I would read the entire file into a char **, then randomly select one as a variable. I think the best code example is at: http://www.cplusplus.com/reference/clibrary/cstdio/fread/

Meanwhile:
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <ctime>
#include <vector>
#include <string>
#include <iomanip>
#include <fstream>
#include <cstdlib>
#include <iostream>

int main ()
{
	srand(unsigned(time(0)));

	std::ifstream fin("words.txt"); // File Read
	std::vector <std::string> words;
	std::string tmp, secretWord;
	while (fin.good())
	{
		getline(fin, tmp);
		words.push_back(tmp);
	}
	
	unsigned randIndex = rand() % words.size();
	secretWord = words.at(randIndex); 
	unsigned strSize = secretWord.length();

	std::string guessWord = std::string(strSize, '*');
	bool runtime = true;

	while (runtime)
	{
		std::cout << std::setw(unsigned((strSize/2) + 40)) << guessWord << "\nYour Guess?\n >";
		std::getline(std::cin, tmp);

		if (tmp == secretWord)
		{
			std::cout << "You Win!\n";
			runtime = false;
		}
		else
			std::cout << "Bad Guess. Try again.\n";
	}

	return 0;
}
Topic archived. No new replies allowed.