如何在C ++中忽略文件中的空格来读取单词?

时间:2018-04-23 19:24:54

标签: c++ fstream ignore

在我的文件中,每一行都是这样的:

“ID:HH-123AB,品牌:梅赛德斯 - 奔驰,128000英里,12升\ n”

ID :,品牌:里程,L在每一行都是相同的。 我只能扫描HH-123AB,梅赛德斯 - 奔驰,128000和12?

1 个答案:

答案 0 :(得分:1)

您可以使用以下函数“标记”字符串

vector<std::string> tokens(const std::string& csv, char separatedBy) {
    vector<std::string> tokenized;
    stringstream str(csv);
    while(!(str.fail())) {
        std::string token;
        getline(str, token, separatedBy);
        tokenized.push_back(token);
    }

    // Used std::move for performance only, you
    //   could just return it, but it will be
    //   copied
    return std::move(tokenized);
}

此函数通过使用分隔符将其拆分来“标记”字符串。

然后,在你的主要功能上:

std::string line;
// Get the whole line
getline(cin, line);
// Get all "comma separated tokens"
vector<std::string> commaSeparated = tokens(line, ',');

然后根据需要解析它的每个部分,例如:

// First space separated token in the first comma separated one
cout << tokens(commaSeparated[0], ' ')[1] << "\n";
// Second space separated token in the second comma separated one
// Note: The first space is considered one
cout << tokens(commaSeparated[1], ' ')[2] << "\n";
// First space separated token in the third comma separated one
cout << tokens(commaSeparated[2], ' ')[1] << "\n";
// First space separated token in the fourth comma separated one
cout << tokens(commaSeparated[3], ' ')[1] << "\n";