У меня есть .txt
файл, который выглядит так...
City- Madrid
Colour- Red
Food- Tapas
Language
Rating
В принципе, я хочу, чтобы добавить все до -
или конец строки (пробел) в один массив, и все после того, как во второй массив.
Мой код добавляет все до -
или whitespace
в один массив, но не все остальные.
{
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
}
}
}
Был бы очень признателен, если бы кто-то помог мне с выражением else.
Если вы собираетесь написать код C++, проще всего будет использовать std::string
. Сюда:
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
}
Если вы хотите придерживаться строк стиля C, вы должны использовать 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
}
Но на самом деле предпочитают std::string
.
new
с не нужно. Я скажу вам, если у вас утечка памяти, но этот код не скомпилируется.