2017-04-14 53 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 
相关问题