using strtok to parse c-strings
Feb 12, 2014 at 7:27pm UTC
I have a coding assignment that provides an irregularly formatted input file (uneven number of spaces) and I'm supposed to use c-strings to separate and format the following information: a students first name, last name, id number, and six test scores. I've been trying to use strtok to separate the string, and so far all I've been able to pull off is an infinite loop. What should I look into to fix this? Thanks!
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
#include <cstring>
#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;
int main()
{
const int MAX_LENGTH = 256;
const int MAX_STUDENTS = 40;
const int MAX_TESTS = 6;
char student_info[MAX_LENGTH];
fstream input_file("student_input.dat" , ios::in);
fstream output_file;
char first_name[10];
char last_name[12];
int eid;
int test_scores[6];
char * string_splitter = strtok(student_info, " " );
string_splitter = strtok(student_info, " " );
while (input_file)
{
while (string_splitter != NULL)
{
for (int index = 0; index < MAX_STUDENTS; index++)
{
input_file.getline(student_info, MAX_LENGTH) >> string_splitter
>> first_name >> string_splitter >> last_name
>> string_splitter >> eid >> string_splitter;
for (int score_getter = 0; score_getter < MAX_TESTS;
score_getter++)
{
input_file >> test_scores[score_getter] >> string_splitter;
}
cout << first_name << " " << last_name << eid << " " ;
for (int test_shower = 0; test_shower < MAX_TESTS;
test_shower++)
{
cout << test_scores[test_shower] << " " ;
}
cout << endl;
}
}
}
}
Feb 12, 2014 at 10:17pm UTC
Isn't cstring a bit outdated? In C++, I would use a string and just use std::getline or parse it right out of the stream.
Topic archived. No new replies allowed.