【问题标题】:Removing characters from C-Style string C++从 C 样式字符串 C++ 中删除字符
【发布时间】:2015-01-13 17:12:34
【问题描述】:

我有一个看起来像这样的.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 语句,我将不胜感激。

【问题讨论】:

  • 这些news 都不是必需的。我会告诉你如果你泄漏内存但这段代码不会编译。

标签: c++ c arrays char cstring


【解决方案1】:

如果您要编写 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

【讨论】:

    猜你喜欢
    • 2022-01-09
    • 2011-12-10
    • 1970-01-01
    • 1970-01-01
    • 2010-12-02
    • 2012-06-25
    • 2019-11-09
    相关资源
    最近更新 更多