我无法将Excel中的输入字符串存储为二维字符串

时间:2017-04-14 12:47:17

标签: c++

我无法将Excel中的字符串存储为二维字符串。

const team = {
  hank: ['good guy', 'wonderful man'],
  chuck: ['jerk', 'buttmunch']
}

const msgCheck = (msg) => Object.keys(team).filter((k) => msg.indexOf(k) > -1)

console.log(msgCheck('tell me about chuck'))
console.log(msgCheck('tell me about hank'))
console.log(msgCheck('tell me about chuck and hank'))

1 个答案:

答案 0 :(得分:0)

如果您想将逗号分隔的文件存储到ifstream的字符串中,我认为您无法这样做。
为什么吗

说我们有这个文件:

one,two,three
four,five,six
seven   ,  eight, nine
ten,    ten,   ten  

如果您使用,作为ifstream(getline)函数的分隔符,它首先会先读取one然后two然后three\nfour。因为分隔符是,而不是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