2014-11-14 77 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