我正在逐行读取文本文件,其内容用逗号分隔,并通过将getline()解压缩到我的stringColor,stringName,stringReward变量中进行解析,传入我的stringstream ss,然后传递给我的tileArray指针数组到相应的int,string和int变量中。将字符串解析为字符串指针数组时出现分段错误错误
我的程序编译,但是当我运行它时,它会生成一个分段错误11,看起来似乎是我将行内容传递到stringstream的地方。我找不到问题出在哪里......
也许如果有人能指出错误的地方,我会非常感激。
这是我试图从文本文件中读入的每一行的格式。 它应该能够读取任意数量的行。
0,瓷砖1,5-
4,瓷砖2,0
2,瓷砖4,1
#include <stdio.h>
#include <string>
#include <fstream>
#include <sstream>
#include <iostream>
#include <stdlib.h>
using namespace std;
typedef struct
{
int color;
string name;
int reward;
}tile;
int main()
{
string line;
int numberOfLines = 0;
ifstream inputFile("inputFile.txt");
if (inputFile.is_open())
{
while(getline(inputFile, line))
{
++numberOfLines; //value to set tile amount
cout << numberOfLines <<endl;
}
tile *tileArray = new tile[numberOfLines];
string stringColor, stringName, stringReward; //declare these values as strings and later convert
stringstream ss; //stringstream variable to convert string variable
for(int n = 0; n<(numberOfLines-1); n++)
{
getline(inputFile, stringColor, ','); //delimiter at first comma
cout << stringColor << endl;
getline(inputFile, stringName, ','); // delimiter at second
cout << stringName << endl;
getline(inputFile, stringReward); // stop at the end of the line
cout << stringReward << endl;
ss<<stringColor;
ss>>tileArray[n]->color;
ss.str("");
ss.clear();
cout << tileArray[n]->color;
ss<<stringName;
ss>>tileArray[n]->name;
ss.str("");
ss.clear();
cout << tileArray[n]->name;
ss<<stringReward;
ss>>tileArray[n]->reward;
ss.str("");
ss.clear();
cout << tileArray[n]->reward;
}
}
return 0;
}
哪里的指针数组?你有一个'tile'数组,但我没有看到指针数组。顺便说一句,指针数组将是:'新的瓦* [24];' – 2015-01-26 18:13:12
也许如果你可以使用调试器,并告诉我们哪一行导致的问题。 – 2015-01-26 18:13:49
我建议你删除数组并使用'std :: vector'。你会有更少的问题。 – 2015-01-26 18:14:43