Removing characters from C-Style string C++

722 views Asked by At

I have a .txt file that looks like this...

City- Madrid
Colour- Red
Food- Tapas
Language
Rating

Basically, I want to add everything before the - or end of line (whitespace) into one array and everything after into a second array.

My code adds everything before the - or whitespace to one array fine but not the rest.

{
   char** city;
   char** other;
   city = new *char[5];
   other = new *char[5];
   for (int i=0; i<5; i++){
      city = new char[95];
      other = new char[95];
      getline(cityname, sizeof(cityname));
      for(int j=0; j<95; j++){
        if(city[j] == '-'){
             city[j] = city[95-j];
        }
        else{
             other[j] = city[j]; // Does not add the everything after - character
        }
      }
}

Would really appreciate it if someone could help me with the else statement.

1

There are 1 answers

0
Barry On

If you're going to write C++ code, the easiest thing to do would be to just use std::string. That way:

std::string line;
std::getline(file, line);
size_t hyphen = line.find('-');
if (hyphen != std::string::npos) {
    std::string key = line.substr(0, hyphen);
    std::string value = line.substr(hyphen + 1);
}
else {
    // use all of line
}

If you want to stick with C-style strings, then you should use strchr:

getline(buffer, sizeof(buffer));
char* hyphen = strchr(buffer, hyphen);
if (hyphen) {
    // need key and value to be initialized somewhere
    // can't just assign into key since it'll be the whole string
    memcpy(key, buffer, hyphen); 
    strcpy(value, hyphen + 1);  
}
else {
    // use all of buffer
}

But really prefer std::string.