字谜程序的单词表传输

发布于 2024-11-30 06:57:04 字数 720 浏览 1 评论 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
 }

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

程序

I'm almost finished with my program, but there's one last bug that I'm having problems ferreting out. The program is supposed to check about 10 scrambled words against a wordlist to see what the scrambled words are anagrams of. To do this, I alphabetized each word in the wordlist (apple would become aelpp), set that as the key of a map, and made the corresponding entry the original, unalphabetized word.

The program is messing up when it comes to the entries in the map. When the entry is six characters or less, the program tags a random character on the end of the string. I've narrowed down what can be causing the problem to a single loop:

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
 }

And if it's necessary, here's the entire program:

Program

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

战皆罪 2024-12-07 06:57:04

防止问题,使用普通函数:

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

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

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

Prevent issues, use normal functions:

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

Prevent more issues, use standard strings:

std::string strInit, str;
while (std::getline(myFile, str)) {
    strInit = str;
    // do stuff
}
海螺姑娘 2024-12-07 06:57:04

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

Best not to use raw C arrays at all! Here's a version, using modern 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
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文