2014-11-14 68 views
0

我基本上有一个txt文件看起来像这样...截断和删除字符

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

我想Map:或空白和Time之前一切存储到一个数组和一切在另一个之后。对于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)); 
    } 
    } 
} 
+2

你'新''但你从不'删除[]',这会泄漏内存。相反,使用'std :: string'和'std :: vector',所以你不需要直接分配内存(然后你也不需要使用C的字符串函数)。 – crashmstr 2014-11-14 20:48:27

回答

0

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

#include <cstring> 

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

文档here

如果发生不是空ptr,则查看发生是否在get line的行末尾。如果不是,那么你的价值就是之后的一切:

+0

谢谢。空白怎么样?例如,'map'后面没有冒号,但我想将'map'后的所有内容都保存为'null'。如果您可以帮助修改我的代码,我将非常感激。 – 2014-11-14 21:20:42

+1

您可以使用bool isspace(char c)函数。说实话,这是非常c字符串相关的代码,并将受益于切换到C++ #include 如果你可以 – user2913685 2014-11-14 21:26:03

+0

是的,但我想学习一些很好的ol' C. – 2014-11-14 23:21:41

0

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 
+0

感谢这种替代方法。由于我的代码被用于游戏的高分,所以我愿意学习新的选择。至于我的'c风格'的方法,我怎样才能让它做'string'所做的事情? – 2014-11-14 23:09:48

+0

编译为C++,包含适当的头文件。在C++上阅读好的参考书? – 2014-11-14 23:23:52