직접 파일을 읽으면 놓칠 수 있는 경우가 많기 때문에 C++에서 CSV 파일을 구문 분석하려면 라이브러리를 사용해야 합니다. C++용 부스트 라이브러리는 CSV 파일을 읽기 위한 정말 좋은 도구 세트를 제공합니다. 예를 들어,
예시
#include<iostream>
vector<string> parseCSVLine(string line){
using namespace boost;
std::vector<std::string> vec;
// Tokenizes the input string
tokenizer<escaped_list_separator<char> > tk(line, escaped_list_separator<char>
('\\', ',', '\"'));
for (auto i = tk.begin(); i!=tk.end(); ++i)
vec.push_back(*i);
return vec;
}
int main() {
std::string line = "hello,from,here";
auto words = parseCSVLine(line);
for(auto it = words.begin(); it != words.end(); it++) {
std::cout << *it << std::endl;
}
} 출력
이것은 출력을 제공합니다 -
hello from here
또 다른 방법은 구분 기호를 사용하여 줄을 분할하고 배열로 가져오는 것입니다. −
예시
또 다른 방법은 getline 함수를 사용하여 문자열을 분할하는 사용자 지정 구분 기호를 제공하는 것입니다 -
#include <vector>
#include <string>
#include <sstream>
using namespace std;
int main() {
std::stringstream str_strm("hello,from,here");
std::string tmp;
vector<string> words;
char delim = ','; // Ddefine the delimiter to split by
while (std::getline(str_strm, tmp, delim)) {
// Provide proper checks here for tmp like if empty
// Also strip down symbols like !, ., ?, etc.
// Finally push it.
words.push_back(tmp);
}
for(auto it = words.begin(); it != words.end(); it++) {
std::cout << *it << std::endl;
}
} 출력
이것은 출력을 제공합니다 -
hello from here