如果你想一個逗號分隔的文件存儲到字符串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