我几乎完成了我的程序,但我在查找最后一个bug时遇到了问题。该程序应该检查大约10个扰乱的单词与词表,看看这些扰乱的单词是什么字形。为此,我将单词列表中的每个单词按字母顺序排列(apple将变为aelpp),将其设置为map的关键字,并将相应的条目设置为原始的未按字母顺序排列的单词。
当涉及到地图中的条目时,程序搞乱了。当条目少于或等于六个字符时,程序会在字符串的末尾标记一个随机字符。我已经将可能导致问题的原因缩小到一个循环:
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
发布于 2011-08-18 07:05:32
防止问题,使用正常功能:
getline(str, 30);
strncpy(strInit, str, 30);防止更多问题,使用标准字符串:
std::string strInit, str;
while (std::getline(myFile, str)) {
strInit = str;
// do stuff
}发布于 2011-08-18 07:05:20
最好不要使用原始的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
}https://stackoverflow.com/questions/7100559
复制相似问题