【问题标题】:How to read in a set of values from a text file, then go to the next line and do the same如何从文本文件中读取一组值,然后转到下一行并执行相同操作
【发布时间】:2013-05-28 12:18:49
【问题描述】:

我正在尝试阅读这样的列表

James  John 15 5 1
Douglas Frank 23 8 1
Bnejamin Zach 17 1 4

并将每个值存储到一个单独的变量中。名称是字符串,其他数字是浮点数和整数。到目前为止,我可以从一行获取数据,但我不知道如何进入下一行并做同样的事情。到目前为止,这是我的代码。

#include <iostream>
#include <string>
#include <fstream>


using namespace std;

int main()
{
ifstream employees;
string lastname, firstname, lastname1, firstname1, lastname2, firstname2;
float base, sales, base1, sales1, base2, sales2;
int years, years1, years2;


employees.open("employees.txt");

while (employees)

  {
employees >> lastname >> firstname >> base >> sales >> years;

我想让它尽可能简单,我还不知道用户定义的函数、数组或向量。那么是否有一个简单的功能可以在几年后结束?并转到下一行并继续?

谢谢。

【问题讨论】:

    标签: c++ iostream


    【解决方案1】:

    使用数组。每当你最终得到“我想给这个变量添加一个数字,因为我想要多个”时,如果这个数字超过 2,那么你真的应该使用一个数组(除非非常特殊的情况)。

    您可能还想使用结构来存储不同的值(名字、姓氏、基数、销售额和年份) - 这样,您只会得到一个数组,而不是几个不同的数组。

    由于这是 C++,因此数组表示 vector。换句话说:

    struct employee
    {
        string firstname, lastname;
        float base, sales;
        int years;
    };
    
    
    vector<employee> emp_table;
    
    employee e;
    
    while (employees >> e.firstname >> e.lastname >> e.base >> e.sales >> e.years)
    {
        emp_table.push_back(e); 
    }
    

    注意,我将员工的输入作为 while 条件。这避免了额外的循环迭代并在您到达文件末尾时“推回”最后一个条目的第二个副本。

    【讨论】:

      【解决方案2】:

      C++ 中有很多方法可以完成您想要做的事情。允许数据验证的一种方法是使用std::getline 函数一次读取一行文件,然后使用std::stringstream 解析数据。这允许您验证数据并继续处理如果数据一行格式不正确。

      [正如 Mats 所说,您可以使用数据结构和 std::vector 来更轻松地存储和管理数据。]

      #include <fstream>
      #include <sstream>
      #include <string>
      #include <vector>
      
      
      struct employee
      {
          std::string firstname;
          std::string lastname;
          float base;
          float sales;
          int years;
      };
      
      int main()
      {
      
          std::ifstream employeeFile;
          employeeFile.open("employees.txt");
      
          std::string tmpLine;
          std::vector<employee> employeeTable;
      
          // read in an entire line at a time 
          while(std::getline(employeeFile, tmpLine))
          {
              // Place the input line into a stream that reads from
              // a string instead of a file.
              std::stringstream inputLine(tmpLine);
      
      
              // Try parsing the data. The ! operator is used here to check
              // for errors. Since we expect the data to be in a specific format
              // we want to be able to handle situations where the input line
              // may be malformed. For example, encountering a string where
              // a number should be.
              employee e;
              if(!(inputLine >> e.firstname >> e.lastname >> e.base >> e.sales >> e.years))
              {
                  // ... error parsing input. Report the error
                  // or handle it in some other way.
      
                  continue;   // keep going!
              }
      
              // Add to the vector
              employeeTable.push_back(e);
          }
      
          return 0;
      }
      

      【讨论】:

        【解决方案3】:

        您可以在循环中使用getline 来检索每一行,然后将其与stringstream 一起使用

        类似:

        string line;
        while(getline(employees,line))
        {
          //doSomething
        }
        

        如果你不能用数组方便的存储,你可以放一个计数器来知道你在哪一行,但这非常重复,而且你的文件中的行数不能变化:

        string line;
        for (int count = 1 ; count <= 3 ; count++)
        {
          getline(employees,line);
          istringstream iss(line);
          if (count == 1)
          {
            iss >> lastname >> firstname >> base >> sales >> years;
          }
          else if (count == 2)
          {
            iss >> lastname1 >> firstname1 >> base1 >> sales1 >> years1;
          }
          else if (count == 3)
          {
            iss >> lastname2 >> firstname2 >> base2 >> sales2 >> years2;
          }
        }
        

        【讨论】:

          【解决方案4】:

          正确打开和读取文件比了解数组是什么更难。如果不使用数组,则必须使用太多变量来保存所有数据,并且必须重复编写代码以从文件中读取,而不是在循环中编写一次。

          #include <iostream>
          #include <string>
          #include <fstream>
          
          using namespace std;
          
          int main()
          {
          
              string firstNames[3];
              string lastNames[3];
              float heights[3];
              float weights[3];
              int ages[3];
          
              ifstream infile("data.txt");
          
              if(!infile)
              {
                  cout << "Couldn't open file!" << endl;
                  return 1;
              }
          
              int count = 0;
          
              while (infile >> firstNames[count] 
                            >> lastNames[count]
                            >> heights[count] 
                            >> weights[count] 
                            >> ages[count] ) 
              {
          
                  ++count;
              }
          
          
              infile.close();
          
              for (int i = 0; i<count; ++i) {
                  cout << firstNames[i] << " " 
                       << lastNames[i] << " " 
                       << heights[i] << " "
                       << weights[i] << " "
                       << ages[i] << " " << endl;
              }
          
          
              return 0;
          }
          
          
          --output:--
          James John 15 5 1 
          Douglas Frank 23 8 1 
          Bnejamin Zach 17 1 4 
          

          对比这场灾难:

          #include <iostream>
          #include <string>
          #include <fstream>
          
          using namespace std;
          
          int main()
          {
          
              string firstName0,firstName1, firstName2;
              string lastName0, lastName1, lastName2;
              float height0, height1, height2;
              float weight0, weight1, weight2;
              int age0, age1, age2;
          
              ifstream infile("data.txt");
          
              if(!infile)
              {
                  cout << "Couldn't open file!" << endl;
                  return 1;
              }
          
              infile >> firstName0 >> lastName0 >> height0 >> weight0 >> age0;
              infile >> firstName1 >> lastName1 >> height1 >> weight1 >> age1;
              infile >> firstName2 >> lastName2 >> height2 >> weight2 >> age2;
          
          
              infile.close();
          
              cout << firstName0 << " "
                   << lastName0 << " "
                   << height0 << " "
                   << weight0 << " "
                   << age0 << endl;
          
              cout << firstName1 << " "
                   << lastName1 << " "
                   << height1 << " "
                   << weight1 << " "
                   << age1 << endl;
          
              cout << firstName2 << " "
                   << lastName2 << " "
                   << height2 << " "
                   << weight2 << " "
                   << age2 << endl;
          
              return 0;
          }
          
          --output:--
          James John 15 5 1
          Douglas Frank 23 8 1
          Bnejamin Zach 17 1 4
          

          看看你必须重复的所有代码。

          注意,当你使用数组时,变量名变成了 firstNames[0] (v. firstName0)、lastNames[0] (v. lastName0) 等,还有 firstNames[1] (v. firstName1) 和 lastNames [1](诉姓氏0)。

          【讨论】:

          • 你需要检查count 的值,否则你会得到Indiana Jones and the Kingdom of Undefined Behavior
          猜你喜欢
          • 1970-01-01
          • 2013-06-08
          • 2020-08-11
          • 1970-01-01
          • 2015-10-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-05-27
          相关资源
          最近更新 更多