0

我几乎完成了我的程序,但最后一个错误是我在寻找问题时遇到的问题。该程序应该根据单词列表检查大约 10 个打乱的单词,以查看打乱的单词是什么字谜。为此,我对单词列表中的每个单词进行了字母排序(apple 将变为 aelpp),将其设置为地图的键,并将相应的条目设为原始的、未按字母排序的单词。

当涉及到地图中的条目时,该程序搞砸了。当条目是六个字符或更少时,程序会在字符串末尾标记一个随机字符。我已将可能导致问题的原因缩小到单个循环:

while(myFile){
  myFile.getline(str, 30);
  int h=0;   
  for (; str[h] != 0; h++)//setting the initial version of str
  {
      strInit[h]=str[h]; //strInit is what becomes the entry into the map.
  }
  strInit[h+1]='\0';    //I didn't know if the for loop would include the null char
  cout<<strInit; //Personal error-checking; not necessary for the program
 }

如果有必要,这里是整个程序:

程序

4

2 回答 2

1

预防问题,使用正常功能:

getline(str, 30);
strncpy(strInit, str, 30);

防止更多问题,使用标准字符串:

std::string strInit, str;
while (std::getline(myFile, str)) {
    strInit = str;
    // do stuff
}
于 2011-08-17T23:05:32.250 回答
0

最好不要使用原始 C 数组!这是一个使用现代 C++ 的版本:

#include <string>

std::string str;

while (std::getline(myFile, str))
{
  // do something useful with str
  // Example: mymap[str] = f(str);
  std::cout << str; //Personal error-checking; not necessary for the program
}
于 2011-08-17T23:05:20.097 回答