Reading Input from Text File into Ctype String containing Whitespace

Hey. I am fairly new to C++ and can't figure out how to read set value of characters from a input file into a c-type string. I need to be able to read one string of 20 characters (like a heading to the file) then keep reading different variables of certain length, with spaces in some of them.

Input File looks like:

TTFTFTTTFTFTFFTTFTTF
ABC54102 T FTFTFTTTFTTFTTF TF
DEF56278 TTFTFTTTFTFTFFTTFTTF
ABC42366 TTFTFTTTFTFTFFTTF
ABC42586 TTTTFTTT TFTFFFTF

I figured something like this would work but I got strange output. I know the >> operator skips whitespace, but I couldn't figure out how to get around this with getline.

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
int main()
{
	ifstream infile;
	infile.open("Ch8_Ex6Data.txt");

	char studentid[8];
	char response[20];
	char answersheet[20];

	for(int i = 0; i <= 19; i++)
	{
		infile >> answersheet[i];
		cout << answersheet[i];
	}

	cout << endl;

	while(infile)
	{
		for(int i = 0; i <= 7; i++)
		{
		infile >> studentid[i];
		}

		for(int i = 0; i <= 19; i++)
		{
		infile >> response[i];
		}

		cout << studentid << " " << response << endl;
	}





TTFTFTTTFTFTFFTTFTTF
ABC54102╠╠╠╠╠╠╠╠╪↓B TFTFTFTTTFTTFTTFTFDE╠╠╠╠╠╠╠╠ABC54102╠╠╠╠╠╠╠╠╪↓B
F56278TT╠╠╠╠╠╠╠╠╪↓B FTFTTTFTFTFFTTFTTFAB╠╠╠╠╠╠╠╠F56278TT╠╠╠╠╠╠╠╠╪↓B
C42366TT╠╠╠╠╠╠╠╠╪↓B FTFTTTFTFTFFTTFABC42╠╠╠╠╠╠╠╠C42366TT╠╠╠╠╠╠╠╠╪↓B
586TTTTF╠╠╠╠╠╠╠╠╪↓B TTTTFTFFFTFFTTFABC42╠╠╠╠╠╠╠╠586TTTTF╠╠╠╠╠╠╠╠╪↓B
Press any key to continue . . .
C style strings are terminated by nul characters. Your arrays were not large enough to hold both the extracted input and a nul character, which is why you're seeing the miscellaneous crap in your output.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <fstream>

using std::cout ;
using std::ifstream ;

int main()
{
    ifstream infile("Ch8_Ex6Data.txt");

    char studentid[9];
    char response[21];
    char answersheet[21];

    infile.getline(answersheet,21) ;
    cout << answersheet << '\n' ;

    while ( infile.getline(studentid,9, ' ') && infile.getline(response, 21) )
        cout << studentid << " " << response << '\n' ;
}
Thank you so much! :)
Topic archived. No new replies allowed.