新>>我将如何读取具有3列且每列包含100个数字的文件的文件? [英] new >> how would i read a file that has 3 columns and each column contains 100 numbers into an array?

查看:64
本文介绍了新>>我将如何读取具有3列且每列包含100个数字的文件的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int exam1[100];// array that can hold 100 numbers for 1st column 
int exam2[100];// array that can hold 100 numbers for 2nd column 
int exam3[100];// array that can hold 100 numbers for 3rd column  

int main() 
{ 
  ifstream infile;   

  int num; 
  infile.open("example.txt");// file containing numbers in 3 columns 
     if(infile.fail()) // checks to see if file opended 
    { 
      cout << "error" << endl; 
    } 
       while(!infile.eof()) // reads file to end of line 
      { 
         for(i=0;i<100;i++); // array numbers less than 100 
           { 
        while(infile >> [exam]); // while reading get 1st array or element 
            ???// how will i go read the next number 
            infile >> num; 
          } 
      } 
  infile.close(); 
} 

推荐答案

int exam1[100];// array that can hold 100 numbers for 1st column 
int exam2[100];// array that can hold 100 numbers for 2nd column 
int exam3[100];// array that can hold 100 numbers for 3rd column  

int main() // int main NOT void main
{ 
  ifstream infile;   

  int num = 0; // num must start at 0
  infile.open("example.txt");// file containing numbers in 3 columns 
     if(infile.fail()) // checks to see if file opended 
    { 
      cout << "error" << endl; 
      return 1; // no point continuing if the file didn't open...
    } 
       while(!infile.eof()) // reads file to end of *file*, not line
      { 
         infile >> exam1[num]; // read first column number
         infile >> exam2[num]; // read second column number
         infile >> exam3[num]; // read third column number

         ++num; // go to the next number

         // you can also do it on the same line like this:
         // infile >> exam1[num] >> exam2[num] >> exam3[num]; ++num;
      } 
  infile.close(); 

  return 0; // everything went right.
} 

我假设您每行总是有3个数字.如果您知道确切的行数,请用0到行数之间的for替换while.

I assume you always have 3 numbers per line. If you know the exact number of lines, replace the while with a for from 0 to the number of lines.

这篇关于新&gt;&gt;我将如何读取具有3列且每列包含100个数字的文件的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆