2010-11-10 118 views
0

我写了一个非常简单的函数,它读入可能的玩家名称并将它们存储在地图中供以后使用。基本上在文件中,每一行都是一个新的可能的玩家名字,但由于某种原因,它似乎除了姓氏之外都有一些看不见的新行字符。我的打印输出显示它是这样的...文本文档中的换行符?

nameLine = Georgio 

Name: Georgio 
0 
nameLine = TestPlayer 

Name: TestPlayer 0 

这里是实际的代码。我认为我需要剥离某些东西,但我不确定我需要检查什么。

bool PlayerManager::ParsePlayerNames() 
{ 
    FileHandle_t file; 
    file = filesystem->Open("names.txt", "r", "MOD"); 

    if(file) 
    { 
     int size = filesystem->Size(file); 
     char *line = new char[size + 1]; 

     while(!filesystem->EndOfFile(file)) 
     { 
      char *nameLine = filesystem->ReadLine(line, size, file); 

      if(strcmp(nameLine, "") != 0) 
      { 
       Msg("nameLine = %s\n", nameLine); 
       g_PlayerNames.insert(std::pair<char*, int>(nameLine, 0)); 
      } 

      for(std::map<char*,int>::iterator it = g_PlayerNames.begin(); it != g_PlayerNames.end(); ++it) 
      { 
       Msg("Name: %s %d\n", it->first, it->second); 
      } 
     } 

     return true; 
    } 

    Msg("[PlayerManager] Failed to find the Player Names File (names.txt)\n"); 
    filesystem->Close(file); 
    return false; 
} 
+0

在地图中使用'char *'作为键时要小心。而是使用'std :: string'来表示字符串。 – 2010-11-10 10:27:44

+0

names.txt文件如何显示(它给出了上述结果)? – Default 2010-11-10 10:30:47

+0

你确定ReadLine不读取换行符吗? – Default 2010-11-10 10:33:08

回答

1

ReadLine明确包含它返回的数据中的换行符。只需选中并删除它:

char *nameLine = filesystem->ReadLine(line, size, file); 

// remove any newline... 
if (const char* p_nl = strchr(nameLine, '\n')) 
    *p_nl = '\0'; 

(这样做是覆盖一个新的NUL终止,从而有效地截断该点的ASCIIZ字符串换行符

+0

这很好,谢谢。 – 2010-11-10 11:01:24

+0

很高兴听到 - 不客气。 – 2010-11-10 11:04:29

0

最有可能ReadLine功能也读取换行符。我想你的文件在最后一行没有换行符,因此你不会得到这个名字的换行符。

但是,直到我知道什么filesystem,FileHandle_tMsg是,它是很难确定问题可能会在哪里。

2

你真的需要考虑使用输入输出流。 。和的std :: string上面的代码,如果你使用++构建提供给您的C这么多简单

问题与您的代码:

  1. 为什么哟你分配一个缓冲区的单行是文件的大小?
  2. 你不清理这个缓冲区!
  3. ReadLine如何填充line缓冲区?
  4. 大概nameLine指向begining的line缓冲,如果是这样,在给定的std::map,关键是一个指针(char*),而不是你期待一个字符串,指针是一样的!如果不同(即某种方式你读了一行,然后为每个名字移动指针,那么std::map将包含每个玩家的条目,但是你将无法通过玩家名称找到条目,因为比较将是指针比较而不是字符串比较,因为你期待!

我建议你看看如何实现这一点使用输入输出流,这里是一些示例代码(没有任何测试)

ifstream fin("names.txt"); 
std::string line; 
while (fin.good()) 
{ 
    std::getline(fin, line); // automatically drops the new line character! 
    if (!line.empty()) 
    { 
    g_PlayerNames.insert(std::pair<std::string, int>(line, 0)); 
    } 
} 
// now do what you need to 
} 

不需要做任何手动内存管理,std::map输入std::string