微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何将特定列保存到 C++ 中的数组中?

如何解决如何将特定列保存到 C++ 中的数组中?

我在 .txt 文件中有一组数据,该文件具有任意数量的列,由用户在输入中指定。我想读取该文件,选择其中一列并将其保存在数组中。这样做的最佳方法是什么?

我已经阅读了 thisthisthis,但它们都在代码中建立了特定的列数。我希望它是一些输入,以便代码是“通用的”并将输入中的特定列保存在该数组中。谢谢!

编辑:这是输入外观的示例 - 列(粒子)的总数由用户指定。输出将是来自此数据的其他一些 .txt 数据。

TIME     PART1       PART2       PART3       PART4  
0    0.0147496  934.902 0.0949583   -1192.37    0.0141576   950.604 0.0905118   -1074.44    
1.66667e-005    0.0147497   2804.7  0.0949583   -3577.12    0.0141576   2851.81 0.0905117   -3223.33    
3.33333e-005    0.0147497   4674.5  0.0949582   -5961.86    0.0141577   4753.02 0.0905116   -5372.21    
5e-005  0.0147498   6544.3  0.094958    -8346.6 0.0141578   6654.22 0.0905115   -7521.09    
6.66667e-005    0.01475 8414.09 0.0949578   -10731.3    0.0141579   8555.41 0.0905114   -9669.96

解决方法

我假设用户通过控制台输入了密码。所以你可以使用内置的cin函数来读取输入。您可以使用 for 循环和字符串流来获取值。代码如下;虽然你可能会根据你的需要稍微调整一下

编辑:下面的代码已经编辑了一点。现在它应该可以回答您的问题了。

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
   int n;
   cin >>n; //user needs to input the column number
   fstream newfile;
   //newfile.open("file.txt",ios::out);  // open the file to perform write operation using file object; Activate this function if you want to overwrite
   newfile.open("file.txt",ios::in); //open the file to perform read operation using file object
   if (newfile.is_open())
   {
      string line;
      getline(newfile,line); //skipping the first line
      while(getline(newfile,line))//loop throuhg rest of the lines
      { 
            int temp=n;
            while(temp != 0)//loop until you get to the requied column
            {
                getline(newfile,line,'\t'); //get the vaue separted by tab='\t'. Be sure that the last column also ends in '\t'
                temp--;
            }
            cout<<line<<endl; //now line holds the element on the loop-row of the selected column
      }
      newfile.close(); //close the file object.
   }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。