用c++从输入文件中读取另一行

Read another line from an input file in c++

本文关键字:一行 读取 c++ 输入 文件      更新时间:2023-10-16

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

#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;
}

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

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

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

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

此外,在互联网上搜索"c++读取文件空间分隔"或"c++读文件CSV"。