C++ - 通过在控制台中包含 csv 文件的路径来读取和写入 csv 文件

C++ - Read and write csv files by including their path in console

本文关键字:文件 csv 路径 读取 控制台 C++ 包含      更新时间:2023-10-16

我想使用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;
}