2017-04-14 55 views
0

我無法將Excel中的字符串存儲到二維字符串中。我不能將Excel中的輸入字符串存儲到二維字符串中

#include <iostream> 
#include <string.h> 
#include <fstream> 
#include <sstream> 
using namespace std; 

int main() 
{ 
    ifstream file("input.csv"); 
    string line,cell; 
    string name[5][20]; 
    string period[5][8]; 
    string tname; 
    int pos, i = 0; 

    while(getline(file, line)) { 
     stringstream linestream(line); 
     int j = 0; 
     while(getline(linestream, cell, ',')) { 
      if(j == 0) 
       name[i][j] = cell; 
      else 
       period[i][j - 1] = cell; 
      j++; 
     } 
     i++; 
    } 
+0

哦,我...請修復縮進。 TIA。 – Borgleader

+0

[Duplicate](http://stackoverflow.com/questions/1120140/how-can-i-read-and-parse-csv-files-in-c)? – Ayak973

+3

如果僅使用名稱[i] [0],爲什麼名稱是二維數組? – fzd

回答

0

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