C++ - 通过在控制台中包含 csv 文件的路径来读取和写入 csv 文件
C++ - Read and write csv files by including their path in console
我想使用C++读取和写入csv文件。
约束是我必须在控制台中写入路径。
例如,如果我想读取一个文件,我必须在控制台中写入:Read "filePath"
如果我想写一个文件:Write "filePath" "delimiter"
我已经制作了有效的函数,但没有在控制台中指示路径。
这是我的主要功能:
int main()
{
SudokuGrid sudokuGrid;
bool done = false;
string command;
while (!done) {
cout << "Enter a command :" << endl;
cin >> command;
if (command == "Read") {
sudokuGrid.readGridFromCSVFile("Sudoku.csv");
cout << endl << "Grid read with success !" << endl << endl;
}
else if (command == "Write") {
sudokuGrid.writeCSVFileFromGrid("Sudoku3.csv", *";");
cout << endl << "The file has been created !" << endl << endl;
}
else if (command == "Display") {
cout << "Here is the grid !" << endl << endl;
sudokuGrid.printGrid();
}
else if (command == "Exit") {
done = true;
}
else if (command == "Help") {
cout << "TODO" << endl;
}
else {
cout << "Incorrect Command" << endl << endl;
}
}
return 0;
它可以工作,但我的问题是我直接在 main 函数中写入文件路径,但我希望能够在控制台中编写它。
我试过:
cin >> command >> csvFilePath;
if (command == "Read") {
sudokuGrid.readGridFromCSVFile(csvFilePath);
cout << endl << "Grid read with success !" << endl << endl;
sudokuGrid.printGrid();
}
它可以工作,但只能使用两个输入(命令"读取"和文件路径(,但我也希望能够使用一个输入(显示(或三个输入(写入、文件路径和分隔符(来完成
您可以使用std::getline()
(doc(而不是std::cin
+operator>>
。
这样,无论您给出多少参数,您都可以在字符串中获取整个输入的命令。然后,您可以拆分字符串并将每个参数存储在std::vector<std::string>
中。
SudokuGrid sudokuGrid;
bool done = false;
std::string command;
while (!done) {
cout << "Enter a command :" << endl;
std::getline(std::cin, command); // Get the whole command, with arguments
// Spliting string using Vincenzo Pii answer in given link
size_t pos = 0;
std::vector<std::string> arguments;
while ((pos = command.find(" ")) != std::string::npos) { // this loop destroy command and split it into arguments
arguments.push_back(command.substr(0, pos));
command.erase(0, pos + 1); // 1 is the size of the delimiter entered in find
}
arguments.push_back(command);
然后,您的命令将成为向量的第一个字符串,允许您保留 if-else 条件并处理其中的参数。
对于"读取"条件的示例,您现在将拥有:
if (arguments.at(0) == "Read") {
sudokuGrid.readGridFromCSVFile(arguments.at(1));
cout << endl << "Grid read with success !" << endl << endl;
}
相关文章:
- 正在将csv文件读取为双精度矢量
- 如何选择在 csv 文件中输出的位置
- 有没有办法在不使用 getline() 的情况下从.csv文件中读取?
- 无法读取C++中的 CSV 文件
- 流:CSV 文件中的换行符
- 是否可以使用 Python csv 阅读器读取使用 C++ std::setw 生成的文件?
- 使用从文件(stod、strtod、atof)中提取的数据C++从字符串转换为双精度.csv
- 如何正确格式化csv文件?
- 正在分析CSV文件-C++
- 如何获取组件和搜索 CSV 文件
- C++ 中的 CSV 文件管理(特别是设置标头和每个标头将分别具有的值)
- 无法逐行读取.csv文件
- 非常快速地阅读 CSV 文件
- 该程序将.csv文件中的一系列单词放入数组中,然后随机生成句子.但它不起作用
- CSV文件之间的差异,使用getline()产生不同的结果
- 将 CSV 文件中的双倍值C++到矢量中
- C++ 将 CSV 文件的列写入向量
- 使用getline读取.csv文件时出现问题
- CSV文件未从缓冲区获取数据
- 错误的值是使用c++从CSV文件数据写入数组