所以我运行这段代码来打开一个文件并将一个本地字符与存储在文件中的值进行比较,但是出于一些奇怪的原因,strcmp告诉我“15”等于“17”..任何想法?这很奇怪,因为问题只发生在第17行。这是相关的代码:
...
string line;
size_t found;
size_t nextFound;
char ID[11];
char storage_ID[11] = "15";
//Open the file
ifstream file(FILE);
if (file.is_open())
{
for (int count = 0; count < 25; count++)
{
getline(file,line);
if (file.eof())
{
return;
}
//store object ID
found = line.find(":");
strcpy(ID[count],line.substr(0,found).c_str()); //stores ID from the start of a line until a ":" is found
if(strcmp(storage_ID,ID[count])==0)
{
foundID = true;
}
else
{
foundID = false;
}
这是文件的样子:
...
1:1234567890:101:A123B4CD
2:2234567890:102:B123B4CD
3:3234567890:103:C123B4CD
(this goes on for 20 lines)
感谢您的帮助!
答案 0 :(得分:1)
代码中有错误,你声明char ID[11];
一个包含11个字符的数组,在循环中 count 从0到25分配给ID [count](当count为12时,你正在从文件中读取12个ID,你将写入无效的内存ID [12 - ?])
代码应为:
char ID[11];
...
strcpy(ID,line.substr(0,found).c_str()); //stores ID from the start of a line until a ":" is found
假设没有ID大小&gt; 11