0

I want to convert string from input file to a char array to tokenize the file. This code might have other problems but for now, the compiler says "incompatible types in assignment of ‘const char*’ to ‘char [100]’".

string filename = "foo.txt";
ifstream data(filename.c_str());
string temp;
char str[100];
char* pch;
while (getline(data, temp)){
    str = temp.c_str();
    pch = strtok(str, " ,.");
    while (pch != NULL){
        cout << pch << endl; //Or something else, Haven't gotten around to this part yet.
        pch = strtok (NULL, " ,.");
    }
}

1 Answers1

1

I know this doesn't answer you question, but the answer is really: do it a different way, cause you're in for a world of hurt if you keep up what you're doing...

You can handle this without any magic numbers or raw arrays:

const std::string filename = "foo.txt";
std::ifstream data(filename.c_str());
std::string line;
while(std::getline(data, line)) // #include <string>
{
  std::string::size_type prev_index = 0;
  std::string::size_type index = line.find_first_of(".,");
  while(index != std::string::npos)
  {
    std::cout << line.substr(prev_index, index-prev_index) << '\n';
    prev_index = index+1;
    index = line.find_first_of(".,", prev_index);
    std::cout << "prev_index: " << prev_index << " index: " << index << '\n';
  }
  std::cout << line.substr(prev_index, line.size()-prev_index) << '\n';
}

This code won't win any beaty or efficiency contests, but it surely won't crash on unexpected input. Live demo here (using an istringstream as input instead of a file).

rubenvb
  • 74,642
  • 33
  • 187
  • 332