我想标记一个字符串,并插入一个标记作为键和其余作为地图的值。但是在插入时,我会遇到分段错误。我调试了很长时间,但找不到解决此错误的方法。这里是我的代码:令牌化字符串时的分段错误
while (!fin.eof())
{
char *str1;
char buf[MAX_CHARS_PER_LINE];
fin.getline(buf, MAX_CHARS_PER_LINE);
str1 = new char[strlen(buf)];
int n = 0;
char *token[MAX_TOKENS_PER_LINE] = {};
token[0] = strtok(buf, DELIMITER);
if (token[0])
{
for (n = 1; n < MAX_TOKENS_PER_LINE; n++)
{
token[n] = strtok(0, DELIMITER);
if (!token[n]) break;
}
}
// Forming str1 using the tokens here
strcpy(str1, token[0]);
strcat(str1, ":");
strcat(str1, token[1]);
int key = atoi(token[3]);
// Adding str1 to map
nameId[key] = str1;
}
}
任何帮助将不胜感激!
''而只能在心碎结束(fin.eof()!)。测试读取是否失败,而不是读取之前,因此您不处理错误的数据。 https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong –
为什么你不使用'std :: string',或者至少,存储' std :: string'在地图中? – PaulMcKenzie