我有一个 .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
。
关于c++ - 从 C-Style 字符串 C++ 中删除字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26961715/