将getline与CSV结合使用
我花了将近4个小时来解决这个问题...
I've spent almost 4 hours trying to get past this issue...
我有一个超过100行的文本文件.每行有4个值,以逗号分隔.我希望能够提取每个值并将其保存到变量(v1 ... v4)中.
I have a text file with over 100 rows. Each row has 4 values separated by commas. I want to be able to extract each value and save it into a variable (v1...v4).
我使用了for循环,因为我不会读取文件的全部内容.我只是想暂时让1个工作.
I have used a for loop, as I won't be reading the entire contents of the file. I'm just trying to get 1 working for now.
到目前为止,我已经设法读取了一行.我现在只需要分列.这是我的Uni作业,不允许我使用任何boost或tokeniser类.只是getline和其他基本命令.
So far, I have managed to read a single row. I just need to break the row up now. This is for my Uni assignment, and I am not allowed to use any boost or tokeniser classes. Just getline and other basic commands.
我有此代码:
// Read contents from books.txt file
ifstream theFile("fileName.txt");
string v1, v2, v3, v4, line;
for (int i = 0; i < 1; i++) {
getline(theFile, line, '\n');
cout << line << endl; // This part works fine
getline(line, v1, ","); // Error here
cout << v1 << endl;
getline(line, v2, ","); // Error here
cout << v2 << endl;
getline(line, v3, ","); // Error here
cout << v3 << endl;
getline(line, v4, '\n'); // Error here
cout << v4 << endl;
}
theFile.close();
我得到的错误是-错误:没有匹配的函数可以调用‘getline(std :: string& ;、 std :: string&,const char [2])
The error I get is - error: no matching function for call to ‘getline(std::string&, std::string&, const char [2])
我该如何解决?
getline的分隔符是一个字符.您已使用双引号,"
表示一个字符串(因此,编译器错误表示您已使用 char [2]
-字符串文字包含一个附加字符)'nul').
The delimiter for getline is a character. You have used double-quote marks ","
which represent a string (hence why the compiler error indicates that you've used char[2]
- string literals contain an additional 'nul' character).
使用单引号代替单个字符值:
Single character values are represented using single quotes instead:
getline(myFile, v1, ',');
edit -我刚刚注意到您传递了 string 作为第一个参数,getline不支持该参数(它不会让您检索令牌直接来自字符串).您可能想将字符串填充到 stringstream
中
edit - I've just noticed you're passing a string as the first parameter, which getline doesn't support (it won't let you retrieve tokens directly from a string). You probably wanted to stuff the string into a stringstream
instead
#include <sstream>
// etc ...
std::string csv = "the,cat,sat,on,the,mat";
std::istringstream buffer( csv );
std::string token;
while( std::getline( buffer, token, ',' ) )
{
std::cout << token << std::endl;
}