9.30
软件构造
CSV:
#include <fstream>
#include <iostream>
#include <vector>
#include <string>
// 保存到CSV
void saveToCSV(const std::vector<std::string>& expressions, const std::string& filename) {
std::ofstream file(filename.c_str());
if (!file.is_open()) {
std::cerr << "Unable to open file for writing: " << filename << std::endl;
return;
}
for (std::vector<std::string>::const_iterator it = expressions.begin(); it != expressions.end(); ++it) {
file << *it << std::endl;
}
file.close();
}
// 从CSV读取
std::vector<std::string> readFromCSV(const std::string& filename) {
std::vector<std::string> expressions;
std::ifstream file(filename.c_str());
if (!file.is_open()) {
std::cerr << "Unable to open file for reading: " << filename << std::endl;
return expressions;
}
std::string line;
while (std::getline(file, line)) {
expressions.push_back(line);
}
file.close();
return expressions;
}
int main() {
std::vector<std::string> expressions;
expressions.push_back("2 + 2=4");
expressions.push_back("3 * 4=12");
expressions.push_back("5 - 1=4");
saveToCSV(expressions, "expressions.csv");
std::vector<std::string> loadedExpressions = readFromCSV("expressions.csv");
for (std::vector<std::string>::const_iterator it = loadedExpressions.begin(); it != loadedExpressions.end(); ++it) {
std::cout << *it << std::endl;
}
return 0;
}
浙公网安备 33010602011771号