I’m trying to read a file which has input(time and price) as: 12:23:31 I created a
67 12:31:23 78 [...]struct which holds values of hour,
minutes and seconds. I used strtok to tokenize the individual values
and use atof to store them. However, I’m getting an error when I try
to tokenize the time: cannot convert std::string' to 'char*' for argument 1 to 'char*'
struct time
{
int hours;
int minutes;
int seconds;
double price;
};
int main()
{
string file, input;
time* time_array;
char* tok;
cout << "Enter a file name to read input: ";
cin >> file;
ifstream file_name(file.c_str());
file_name >> input;
file_name >> input;
//while(!file_name.eof())
for(int i = 0; i < 4; i++)
{
time_array = new time;
file_name >> input;
tok = strtok(input, ":"); //ERROR HERE
while(tok != NULL)
{
*time_array.hours = atof(tok[0]);
*time_array.minutes = atof(tok[1]);
*time_array.seconds = atof(tok[2]);
}
file_name >> input;
*time_array.prine = atof(input);
}
}
I would not use
strtokfor this job at all1. If you want to use C-like tools, then read the data with fscanf:Most people writing C++ would prefer something more typesafe though. One possibility would be to use essentially the same format string to read the data using Boost.format.
Another possibility would be to use stream extractors:
As to what this does/how it works: each extractor reads one item from the input stream. the extractors for
floateach read a number. The extractors forchareach read one character. In this case, we expect to see:99:99:99 99, where9means “a digit”. So, we read a number, a colon, a number, a colon, a number and another number (the extractor skips whitespace automatically). The two colons are read intocharvariables, and can either be ignored, or you can check that they really are colons to verify that the input data was in the correct format.Here’s a complete, compileable demo of that technique:
There are certainly a lot more possibilities, but at least those are a few reasonable ones.
strtok, but there are some where I might be at least a little tempted, or wishstrtokweren’t so badly designed so I could use it. In this case, however, I don’t even see much reason to use anything similar tostrtokat all.