在C ++中从输入文件读取另一行

时间:2018-11-04 16:47:30

标签: c++ input output

因此,我尝试从输入文件中读取数据并将其转换为带有条形图的输出文件。我可以打开并读取输入文件,但由于不知道如何继续输入文件中另一组数据的下一行,因此陷入了循环。

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

using namespace std;

int main() {
   ifstream inFile;
   ofstream outFile;
   unsigned int storeNum;
   long long int salesData;
   string fileName;

   cout << "Please enter file name: ";
   cin >> fileName;

   inFile.open(fileName);
   if (inFile) {
      while (inFile >> storeNum >> salesData, '\n')
      {
         if (storeNum < 1 || storeNum > 99)
         {
            cout << "The store number " << storeNum << setw(2) << "is not valid" << endl;
         }
         if (salesData < 0)
         {
            cout << "The sales value for store " << storeNum << setw(2) << " is negative" << endl;
         }
         else {
         outFile.open("saleschart.txt");
         outFile << "SALES BAR CHART" << endl;
         outFile << "(Each X equals 1,000 dollars)" << endl;
         while (storeNum > 0)
         { 
            outFile << "Store " << storeNum << setw(2) << ": ";
            while (salesData > 1000)
            { 
               outFile << "X";
               salesData = salesData - 1000;
            }
            outFile << endl;
         }
         }


      }
      inFile.close();
   }

   else
   {
      cout << "File " << fileName << " could not be opened" << endl;
   }

   system("pause");
   return 0;
}

1 个答案:

答案 0 :(得分:0)

要逐行读取文件,请使用std::getline

std::string text_line;
while (std::getline(inFile, text_line))
{
//...
}

要从字符串中提取数字,请使用std::istringstream

std::istringstream text_stream(text_line);
text_stream >> storeNum >> salesData;

此外,在Internet上搜索“ c ++读取文件空间分隔”或“ c ++读取文件CSV”。