【问题标题】:Truncating and removing characters from char array C++从 char 数组 C++ 中截断和删除字符
【发布时间】:2015-01-12 08:23:23
【问题描述】:

我基本上有一个看起来像这样的txt 文件...

High Score: 50
Player Name: Sam
Number Of Kills: 5
Map
Time

我想将: 之前的所有内容或MapTime 之后的空格存储到一个数组中,然后将所有内容存储在另一个数组中。对于MapTime,后面什么都没有,所以我想将空格存储为null

到目前为止,我已成功读取所有这些信息并将其存储到 temp 数组中。但是,我遇到了麻烦。这是我的代码:

istream operator >> (istream &is, Player &player)
{
  char **temp;
  char **tempNew;
  char lineInfo[200]
  temp = new char*[5];
  tempNew = new char*[5];
  for (int i=0; i<5; i++)
  {
    temp[i] = new char[200];
    is.getline(lineInfo, sizeof(lineInfo));
    int length = strlen(lineInfo);
    for (int z=0; z < length; z++)
    {
      if(lineInfo[z] == '= ' ){  //HOW DO I CHECK IF THERE IS NOTHING AFTER THE LAST CHAR
        lineInfo [length - (z+1)] = lineInfo [length];
        cout << lineInfo << endl;
        strncpy(temp[i], lineInfo, sizeof(lineInfo));
      }
      else{
        tempNew[i] = new char[200];
        strncpy(tempNew[i], lineInfo, sizeof(lineInfo));
    }
  }
}

【问题讨论】:

  • new,但你从来没有delete [],这会泄漏内存。相反,使用std::stringstd::vector 这样您就不需要直接分配内存(然后您也不需要使用C 字符串函数)。

标签: c++ c arrays char


【解决方案1】:

如果你需要的是找到':'

#include <cstring>

而且只是 auto occurance = strstr(string, substring);

文档here

如果出现不是空指针,则查看出现是否在 get 行的行尾。如果不是,那么您的价值就是之后的一切:

【讨论】:

  • 谢谢。空格呢?例如,map 之后没有冒号,但我想将map 之后的所有内容存储为null。如果您能帮助修改我的代码,将不胜感激
  • 可以使用 bool isspace(char c) 函数。老实说,这是与 c 字符串相关的代码,如果可以的话,将受益于切换到 c++ #include
  • 那么最好用 c 语言完成所有工作并使用函数式编程。为什么使用 C++?
【解决方案2】:

std::string 更容易。

// Read high score
int high_score;
my_text_file.ignore(10000, ':');
cin >> high_score;

// Read player name
std::string player_name;
my_text_file.ignore(10000, ':');
std::getline(my_text_file, player_name);  

// Remove spaces at beginning of string
std::string::size_type end_position;
end_position = player_name.find_first_not_of(" \t");
if (end_position != std::string::npos)
{
  player_name.erase(0, end_position - 1);
}

// Read kills
unsigned int number_of_kills = 0;
my_text_file.ignore(':');
cin >> number_of_kills;

// Read "Map" line
my_text_file.ignore(10000, '\n');
std::string map_line_text;
std::getline(my_text_file, map_line_text);

// Read "Text" line
std::string text_line;
std::getline(my_text_file, text_line);

如果您坚持使用 C 风格的字符串(char 的数组),您将不得不使用更复杂且安全性更低的功能。查找以下函数:

fscanf, strchr, strcpy, sscanf

【讨论】:

  • 感谢这种替代方法。由于我的代码被用于游戏中的高分,我愿意学习新的替代方案。至于我的c style 方法,我将如何让它做你对string 所做的事情?
  • 编译为 C++,包含适当的头文件。阅读有关 C++ 的优秀参考书?
猜你喜欢
  • 2014-03-19
  • 1970-01-01
  • 2022-01-06
  • 1970-01-01
  • 2021-06-20
  • 1970-01-01
  • 1970-01-01
  • 2018-01-28
  • 1970-01-01
相关资源
最近更新 更多