getline 忽略 '\n' - 带有两个分隔符的 getline

getline ignores '\n' - getline with two delimiters

在 C++ 中,我得到一个矩阵的 csv 文件,每行的形式分别为 float,float,float,\nfloat float float \n

如果我使用 getline 逐行读取文件,结束行定界符 \n 也总是被读取,即 getline(csv_file, csv_line, '\n')getline(csv_file, csv_line) 作为输出给出 1,2,3,\n 而不是我期望的 1,2,3, 。我怎样才能明确丢弃这个 \n?

此外,我如何区分这两个输入版本并存储特定的分隔符 ' '','

首先,让数据以每行不同的格式呈现通常不是一个好主意。

但是如果是,你可以把所有的行都读成字符串,使用this getline with no delimeter and then parse string using regexp or simple string functions. You can define which format it is by trying to find , symbol at string. If you find它,那么你需要用逗号分隔,否则用空格分隔。

另请查看 stringstream class (link)。它仅适用于您需要从已读取的字符串中切出一些值(而不仅仅是一种类型)的情况。