【问题标题】:convert 2d string array to 1D float ,int arrays将二维字符串数组转换为一维浮点、整数数组
【发布时间】:2016-07-09 13:58:17
【问题描述】:

对于一个项目,我想读取不同数组中的文本文件的列。首先,我在一个二维字符串数组中读取文件,并将该数组拆分为不同的intfloat 一维数组。但是当我使用atofatoi 方法将数字转换为floatint 时,我遇到了分段错误。有人有其他解决方案吗?

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

标签: c++ arrays atoi atof


【解决方案1】:

我已经运行了一个调试器,但在索引 0 处出现错误,其值为“7,701”,并带有后续行。

电压[i]= atof(word[50][0].c_str());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-23
    • 1970-01-01
    • 1970-01-01
    • 2018-08-08
    • 2013-03-28
    • 1970-01-01
    相关资源
    最近更新 更多