【发布时间】:2020-03-17 16:35:49
【问题描述】:
我想强调以下一个基本问题:
假设您有一个 CSV 文件并使用输入标题填充单元格
代码应从 .csv 文件中读取此内容并将结果写入 .csv 文件。还可以对输出案例总数加上案例平均值进行编码。这是一个示例表单,我想看看如何有效地采用它来完成这个基本示例。
void create()
{
// file pointer
fstream fout;
// opens an existing csv file or creates a new file.
fout.open("reportcard.csv", ios::out | ios::app);
cout << "Enter the details of 5 students:"
<< " roll name maths phy chem bio";
<< endl;
int i, roll, phy, chem, math, bio;
string name;
// Read the input
for (i = 0; i < 5; i++) {
cin >> roll
>> name
>> math
>> phy
>> chem
>> bio;
// Insert the data to file
fout << roll << ", "
<< name << ", "
<< math << ", "
<< phy << ", "
<< chem << ", "
<< bio
<< "\n";
}
}
另外,读取特定记录
void read_record()
{
// File pointer
fstream fin;
// Open an existing file
fin.open("reportcard.csv", ios::in);
// Get the roll number
// of which the data is required
int rollnum, roll2, count = 0;
cout << "Enter the roll number "
<< "of the student to display details: ";
cin >> rollnum;
// Read the Data from the file
// as String Vector
vector<string> row;
string line, word, temp;
while (fin >> temp) {
row.clear();
// read an entire row and
// store it in a string variable 'line'
getline(fin, line);
// used for breaking words
stringstream s(line);
// read every column data of a row and
// store it in a string variable, 'word'
while (getline(s, word, ', ')) {
// add all the column data
// of a row to a vector
row.push_back(word);
}
// convert string to integer for comparision
roll2 = stoi(row[0]);
// Compare the roll number
if (roll2 == rollnum) {
// Print the found data
count = 1;
cout << "Details of Roll " << row[0] << " : \n";
cout << "Name: " << row[1] << "\n";
cout << "Maths: " << row[2] << "\n";
cout << "Physics: " << row[3] << "\n";
cout << "Chemistry: " << row[4] << "\n";
cout << "Biology: " << row[5] << "\n";
break;
}
}
if (count == 0)
cout << "Record not found\n";
}
[1]: https://i.stack.imgur.com/q6VfZ.png
【问题讨论】:
-
您忘记了c++ 标签。这看起来不是很小(如minimal reproducible example),而且也很难理解你有什么问题。您在代码上方提到的示例数据似乎与代码没有任何关系。该代码处理移动平均线等。
-
添加了标签 C++。此外,还添加了一项声明,即平均病例总数也在愿望清单中。我不能从头开始创建一个最小值,因为 SO 中有很多示例,问题是如何导航以修改它们,以便为新用户 C++ 进行最基本的练习——就像我在这个问题上提出的那样。您能为这项倡议做出贡献吗?
-
恐怕你误解了这个网站应该如何运作。人们通常不会为您执行/调整。相反,请尝试自己做,如果遇到困难,请向minimal reproducible example 提出您需要帮助的一个问题。
-
您有简单的逗号分隔数据,还是带有引号和引号之类的花哨的 CSV 格式?
-
现在好多了,虽然不是minimal reproducible example。如果没有人超过我,我会做出回答。 :-)