【发布时间】:2016-07-09 13:58:17
【问题描述】:
对于一个项目,我想读取不同数组中的文本文件的列。首先,我在一个二维字符串数组中读取文件,并将该数组拆分为不同的int 或float 一维数组。但是当我使用atof 或atoi 方法将数字转换为float 的int 时,我遇到了分段错误。有人有其他解决方案吗?
void Tftdiag::readFile(std::string file)
{
string testline;
char tab2[1024];
strcpy(tab2, file.c_str());
ifstream Test( tab2 );
if (!Test)
{
cout << "There was an error opening the file.\n";
}
//store words in array
int x=0,y=0;
while( Test>>testline )
{
word[y][x]=testline;
x++;
if (testline=="")
y++;
}
//output whole array with array position numbers for each entry
cout<<"Array contents:\n";
for (int y=0;y<50;y++)
{
for (int x=0;x<6;x++)
cout<<word[y][x]<<"("<<y<<","<<x<<")"<<endl;
}
for(int i=0; i<50; i++) {
voltage[i]= atof("0.5".c_str());
//currentArray[i]= atof(word[50][1].c_str());
//lux[i]= ::atof(word[50][2].c_str());
//red[i]= atoi(word[50][3].c_str());
//green[i]= atoi(word[50][3].c_str());
//blue[i]= atoi(word[50][3].c_str());
}
}
【问题讨论】:
-
就个人而言,我更喜欢使用
std::stoi()而不是atoi()。试试看,也许对你有帮助 -
word的第一个维度的大小为 50。因此您只能访问直到size - 1(49) 之前的元素。 -
表达式
"0.5"不是一个对象,你不能在它上面使用成员函数,所以应该会给你一个编译器错误。事实上,像"0.5"这样的字符串文字会给你一个指向char const*类型的第一个元素的指针,这正是atof想要的,所以不需要在std::string对象中使用任何包装。 -
@JoachimPileborg 我已将行更改为 'voltage[i]=atof(word[50][0].c_str())' 但仍然存在分段错误。
-
@BlitzRakete for 循环的索引达到最大值。到 49