storing a line from a text file into a cstring

This program is supposed to grab an answer key from the first line of a file. I have to use c-strings for the assignment which is very annoying. I thought I had it but the function only put the letter F in the output file. This is what a example input file would look like :

ACDBCBDCCACDACC
George Washington abcdabcdabcdccc
John Adams abaa aaccacdacc

The top line is the answer key and the rest is supposed to be used to check if the students got answers wrong/right.

Here is my code so far:

The function get_key is supposed to get the first line and store it in the c-string char key[50] but it is not returning correctly. I got it to return the last for letters of the line but that is the closest I have got. Thanks for any help.

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
45
46

void get_key(string in_file,string out_file);
void get_files(string& in_file,string& out_file);

 
int main (int argc, char const *argv[])
{
	string in_file,out_file;
	get_files(in_file,out_file);
	get_key(in_file,out_file);
	return EXIT_SUCCESS;
}

void get_files(string& in_file,string& out_file)
{	
	cout << "Enter the file you are taking input from: ";
		cin >> in_file;
	cout << "Enter the file you are outputting to: ";
		cin >> out_file;
}

void get_key(string in_file,string out_file)
{
	int count = 0;
	int i;
	string word;
	char key[50];
	ofstream outf;
	ifstream inf;

	outf.open(out_file.c_str());
	inf.open(in_file.c_str());

	if (inf.fail()|| outf.fail())
	{
		exit(1); //terminate the program
	}
	
	inf.getline(key, 50);
	
	outf << key[50];
	
	inf.close();
	outf.close();
	
}
Last edited on
Use the istream::getline() function to read C-strings.
http://www.cplusplus.com/reference/istream/istream/getline/

Hope this helps.
That helped. Thank You. Now I am trying to get the Names from the file and be able to separate them from the answers on the left side. Any advice?
Not being able to use std::strings is annoying.

You can search through the string to find spaces, and copy out string data that way.

If the file format is fixed, you can inf.getline() with a space as delimiter for the first name, last name, etc, and just inf.getline() without any explicit delimiter (newline) for the final item on the line.
Topic archived. No new replies allowed.