从字符数组C++中截断和删除字符

Truncating and removing characters from char array C++

本文关键字:字符 删除 数组 C++      更新时间:2023-10-16

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

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

我想将:之前的所有内容或Time Map之后的空格存储到一个数组中,并将之后的所有内容存储在另一个数组中。对于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));
    }
  }
}

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

#include <cstring>

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

文档在这里。

如果出现不是

空 PTR,则查看出现是否位于 Get 行的行尾。如果没有,您的值就是之后的所有内容:

使用 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