-1

我正在尝试逐行读取文本文件,然后将每一列作为向量读取,但是当我尝试计算第一列时,它显示为零,即未正确读取文件。

int main(void)
{


    ifstream myfile ("data1.txt");
    string line;


    if (myfile.is_open())
   {

        int ln=1;

     while ( getline (myfile,line) )
     {      
      if(ln==1){ln++; continue;}
        istringstream iss(line);
        string word;
        vector<double> column;
        int w=1;
        while(iss >> word) 
        {   

            //double dw=atof(Form("%s",word));      
            column.push_back(atof(Form("%s",word)));
            cout<<column[0];

        w++;


        }

    ln++;
    cout<<"\n";
    }
   myfile.close();
  }
  //else
  else cout<<"Unable to open file"; 
  cout<<"\n";
  return ;
  }enter code here
4

2 回答 2

0

push_back附加一个元素作为向量的最后一个元素,同时columns[0]始终引用向量的第一个元素。

是第一个元素0

还有问题吗?

(请解释一下是什么Form,举个命令行输入文件和输出的例子)

于 2015-07-27T09:06:28.077 回答
0

首先学习如何缩进并始终使用一些有意义的插入空行的方案。当您这样做时,您可以阅读自己的代码并确定它是否在做您认为的事情。

第二。将 Form("%s",word) 保存在一个字符串中(现在称为 form_string)添加这一行cout<<"form returns "<<form_string<<endl;99.99% 可能它会打印零。

最后更改 cout<<column[0];cout<<column[0]<<" ";cout<<*(column.rbegin())<<" ";。后者打印出您读取的所有值,前者打印出您一遍又一遍地读取的第一个值。

于 2015-07-27T09:46:09.147 回答