【问题标题】:Wordlist transfer for an anagram program字谜程序的单词表传输
【发布时间】:2011-10-29 08:34:19
【问题描述】:

我几乎完成了我的程序,但最后一个错误是我在找出问题时遇到的问题。该程序应该根据单词列表检查大约 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
 }

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

Program

【问题讨论】:

  • Kerrek SB:阅读整个代码文件,它就在那里。

标签: c++ anagram


【解决方案1】:

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

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

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

std::string strInit, str;
while (std::getline(myFile, str)) {
    strInit = str;
    // do stuff
}

【讨论】:

  • ifstream 成员 getline 不接受 std::string 参数。
  • @Kerrek SB:抱歉,我和std::getline混淆了。
  • 非常感谢! strncpy() 为我的程序工作。我对字符串命令不是很熟悉,所以下次遇到类似问题时,也许我应该记得查找它们的列表。
【解决方案2】:

最好不要使用原始 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
}

【讨论】:

  • C 风格的数组中没有这样的东西。
  • @nightcracker:OP 没有说他使用裸数组
  • @nightcracker:你说得对,我把帖子改成了纯 C++ 代码。
  • 哎呀! 你甚至会编写 C++ 代码吗? strInit = str; 怎么了?
猜你喜欢
  • 2020-09-25
  • 2015-07-26
  • 2015-07-27
  • 2011-09-19
  • 2011-02-07
  • 2012-09-10
  • 1970-01-01
  • 2013-09-20
  • 2018-04-10
相关资源
最近更新 更多