我删除了我的旧帖子更精确。我正在使用c ++。我有一个csv;作为分隔符。使用以下代码我读了一行,然后我读取了行的所有元素并将它们转换为int。我的问题是我需要将它们转换为int16_t或int32_t。代码是:
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;
int main (int argc, const char * argv[]) {
string line, csvItem;
ifstream myfile ("modifica1.csv");
int lineNumber = 0;
int lineNumberSought = 7462;
if (myfile.is_open()) {
while (getline(myfile,line)) {
lineNumber++;
if(lineNumber == lineNumberSought) {
istringstream myline(line);
string bus1s;
string bus2s;
string bus3s;
string bus4s;
string bus5s;
string bus6s;
string bus7s;
string bus8s;
string bus9s;
getline(myline,bus1s,';');
getline(myline,bus2s,';');
getline(myline,bus3s,';');
getline(myline,bus4s,';');
getline(myline,bus5s,';');
getline(myline,bus6s,';');
getline(myline,bus7s,';');
getline(myline,bus8s,';');
getline(myline,bus9s,'\n');
int bus1;
int bus2;
int bus3;
int bus4;
int bus5;
int bus6;
int bus7;
int bus8;
int bus9;
bus1=stoi(bus1s);
bus2=stoi(bus2s);
bus3=stoi(bus3s);
bus4=stoi(bus4s);
bus5=stoi(bus5s);
bus6=stoi(bus6s);
bus7=stoi(bus7s);
bus8=stoi(bus8s);
bus9=stoi(bus9s);
}
}
myfile.close();
}
return 0;
}
答案 0 :(得分:-1)
以下是如何将csv文件(包含任何分隔符)解析为vector
tuple
的示例:
#include <sstream>
#include <vector>
#include <string>
#include <tuple>
#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string/trim.hpp>
template<class... ColumnTypes>
class CsvRowParser
{
char const separator_;
template<size_t... Idxs>
std::tuple<ColumnTypes...>
convert_csv_row(std::vector<std::string> const& columns, std::integer_sequence<size_t, Idxs...>) {
return std::tuple<ColumnTypes...>{boost::lexical_cast<ColumnTypes>(boost::algorithm::trim_copy(columns[Idxs]))...};
}
public:
using RowType = std::tuple<ColumnTypes...>;
CsvRowParser(char separator)
: separator_(separator)
{}
RowType parse_row(std::string const& csv_row) {
std::vector<std::string> columns;
boost::algorithm::split(columns, csv_row, [this](char c) { return c == separator_; });
if(columns.size() != sizeof...(ColumnTypes))
throw std::runtime_error("Invalid csv row: " + csv_row);
return convert_csv_row(columns, std::make_index_sequence<sizeof...(ColumnTypes)>{});
}
};
int main() {
std::string my_csv;
my_csv += "abc, 1, 1.1\n";
my_csv += "def, 2, 2.2\n";
std::istringstream s(my_csv);
using Parser = CsvRowParser<std::string, int, double>;
Parser parser(',');
std::vector<Parser::RowType> rows;
for(std::string line; getline(s, line);)
rows.push_back(parser.parse_row(line));
}