如果你想一个逗号分隔的文件存储到字符串ifstream
我认为你不能这样做。
为什么?
说我们有这个文件:如果您使用,
作为分隔符与ifstream
(函数getline)功能,它首先读取one
然后two
然后three\nfour
一起
one,two,three
four,five,six
seven , eight, nine
ten, ten, ten
;因为分隔符为,
,而不是newline
,如果你习惯使用std::regex
可以轻松解决:
首先关闭所有你需要:
std::ifstream input_file_stream("file"); // file stream
std::string string[ 4 ][ 3 ]; // row and column
std::regex regex(R"(\s*,\s*)"); // regex pattern
int row = 0, column = 0;
第二步:
// read from a file line-by-line
for(std::string one_line; std::getline(input_file_stream, one_line);){
// regex_token_iterator as splitter and delimiter is `,`
std::regex_token_iterator<std::string::iterator> first(one_line.begin(), one_line.end(), regex, -1), last;
// loop over each line
while(first != last){
// each time initialize a row
string[ row ][ column++ ] = std::string(*first++);
}
// for the next row
++row;
column = 0;
}
最后
for(const std::string& str : string[ 0 ]) std::cout << str << ' ';
std::cout << '\n';
for(const std::string& str : string[ 1 ]) std::cout << str << ' ';
std::cout << '\n';
for(const std::string& str : string[ 2 ]) std::cout << str << ' ';
std::cout << '\n';
for(const std::string& str : string[ 3 ]) std::cout << str << ' ';
input_file_stream.close();
和输出:
one two three
four five six
seven eight nine
ten ten ten
哦,我...请修复缩进。 TIA。 – Borgleader
[Duplicate](http://stackoverflow.com/questions/1120140/how-can-i-read-and-parse-csv-files-in-c)? – Ayak973
如果仅使用名称[i] [0],为什么名称是二维数组? – fzd