我想標記一個字符串,並插入一個標記作爲鍵和其餘作爲地圖的值。但是在插入時,我會遇到分段錯誤。我調試了很長時間,但找不到解決此錯誤的方法。這裏是我的代碼:令牌化字符串時的分段錯誤
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