void generateSudokuFromCSV(std::ifstream &infile, sudokuT sudoku) {
for (int i = 0; i < 9; i++) {
std::string line;
std::getline(infile, line);
if (!infile.good()) break;
std::istringstream iss(line);
for (int j = 0; j < 9; j++) {
std::string ch;
std::getline(iss, ch, ',');
if (!iss.good()) break;
std::istringstream converter(ch);
converter >> sudoku.board[i][j];
}
}
}
这是我在csv文件中读取并设置数独板的代码。仅当每行中最后一个数字后面有逗号时才有效。这就是文件的样子:
0,8,6,0,5,0,3,0,0
4,0,7,0,9,0,0,0,0
5,2,0,8,7,0,0,0,0
0,5,0,0,8,0,0,0,0
7,1,0,0,4,0,0,6,5
0,0,0,0,2,0,0,1,0
0,0,0,0,1,8,0,4,3
0,0,0,0,6,0,1,0,9
0,0,5,0,3,0,8,7,0
如果文件如下所示,代码可以工作:
0,8,6,0,5,0,3,0,0,
4,0,7,0,9,0,0,0,0,
5,2,0,8,7,0,0,0,0,
0,5,0,0,8,0,0,0,0,
7,1,0,0,4,0,0,6,5,
0,0,0,0,2,0,0,1,0,
0,0,0,0,1,8,0,4,3,
0,0,0,0,6,0,1,0,9,
0,0,5,0,3,0,8,7,0,
但这对于csv来说并不常见,而不是excel如何转换它。那么我怎样才能更改代码来正确处理这个问题。 getline可以采用多个分隔符吗? 感谢您的时间和见解。
答案 0 :(得分:0)
std::getline(iss, ch, ',');
将无法读取最后一个字段。为了解释那个替换线
if (!iss.good()) break;
以下内容:
if (!iss.good())
{
iss.clear();
std::getline(iss, ch);
if ( !iss.good() ) // This is a real problem.
exit(EXIT_FAILURE);
}
答案 1 :(得分:0)
一种可能的解决方案是消除iss
流并直接处理line
字符串。
for (int j = 0; j < 9; j++) {
size_t si = line.find_first_not_of("0123456789");
std::string ch = line.substr(0, si); // substring before delimiter
if (ch.length() == 0) break; // empty string
std::istringstream converter(ch);
converter >> sudoku.board[i][j];
if ((si + 1u) >= line.length() || si == std::string::npos) break; // no more data after delimiter
line = line.substr(si + 1u, std::string::npos); // substring after delimiter
}
如果您想更严格地使用格式,请用
替换查找部分size_t si = line.find_first_of(',');