用c++从输入文件中读取另一行
Read another line from an input file in c++
所以我试图从输入文件中读取数据,并将数据转换为带有条形图的输出文件。我可以打开并读取输入文件,但我陷入了循环,因为我不知道如何转到输入文件中另一组数据的下一行。
#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"。
相关文章:
- 用c++从输入文件中读取另一行
- 读取文件的最后一行并输入到链接列表时出错
- 如何从一行中读取特定数量的字符?(C++)
- 读取最后一行代码算法 - c++ 时出现问题
- 而(!inputfile.eof())只读取第一行?
- 逐字读取文本文件中的每一行并转换为 int(无限循环或崩溃?
- 需要从存档中读取一行文本.txt直到找到"hhh",然后转到下一行
- 从文本文件中读取一行并将其存储在 C++ 中的 2D 矢量中
- 从文件中的一行读取特定数据-C++
- 使用std::getline()读取一行
- 从文本文件中的每一行读取数字,并计算数字重复的次数
- 从文件读取并在一行中写入 cout
- 将 ifstream 文件和每一行读取到数组中
- 从文件 c++ 中的下一行读取
- 在同一行读取具有多个类型的文件
- 写入终端并从同一行读取
- 如何在c++中从最后一行读取文本文件
- 逐行读取数组,每一行读取3个值
- 在同一行读取字符串和整数
- 从一行读取hh:mm格式的时间