首页 > 解决方案 > 允许用户输入信息并发送到文件

问题描述

这是我的第一堂编程课,我无法将信息发送到文件。该程序应该允许用户输入 5 名员工的信息,然后将该文本写入文件。我能够让用户输入和循环正常工作,但我正在努力弄清楚如何将其发送到文件。任何帮助将不胜感激。非常感谢。

     //include necessary header files
     #include <iostream>
     #include <fstream>
     #include <cstdlib> 
     #include <string>
     #include <iomanip> 
     using namespace std;

     int main() 
      {

      string filename = "data.txt";
      ofstream outFile;

      outFile.open(filename.c_str()); 

      if (outFile.fail()) 
      {
        cout << "The file was not successfully opened."; << endl; 
        exit (1);    
      }


      outFile << setiosflags(ios::fixed) << setiosflags(ios::showpoint) << setprecision(2);//for 
      loop

       const int num = 5;
      string sex;
      string name;
      int ID, years;
      double wages;


      for (int i = 0; i < num; i++)

      {
       cout << "ID no.: "; //Enter ID no.  here
        cin >> ID; //reads imput from user
  
        cout << "\n Name: "; //displays message to enter name
        cin >> name;//reads imput from user
  
        cout << "\n Sex (M/F): "; //displays message to enter employee's gender
        cin >> sex;//reads imput from user

        cout << "\n Hourly Wages: "; //displays message to enter hourly salary
        cin >> wages;//reads imput from user
  
        cout << "\n Years with          company: "; //displays message to enter number of years 
      with company
        cin >> years; //reads imput from user
      }


      //declare required variables
      int tempID, tempyears;
      string tempsex;
      string tempname;
       double tempwages;

      outFile.close();
      cout << "The file " << filename << " has been successfully written." << endl;

      return 0;
      }

标签: filestream

解决方案


推荐阅读