0

我正在尝试读取格式为

名字中间名(可选)姓氏宠物名\n

由于中间名出现在一半的条目中,我不确定读取这些条目并将它们放入正确的变量名的最佳方法。任何帮助将不胜感激。

4

2 回答 2

3

你可以这样做:

std::string line, word;
while (std::getline(myFile, line)) {
    if (line.empty()) continue;        

    // read words from line:
    std::istringstream is(line);
    std::vector<std::string> words;
    words.reserve(4);
    for (int i = 0; is >> words && i < 4; i++)
        words.push_back(word);

    if (words.size() == 4)
        // middle name was present ...
    else
        // it was not ...
}
于 2013-10-06T16:00:48.537 回答
1

如果只有 middleName 是可选的,您可以拆分行并将单词保留在std::vector<std::string>. 然后检查大小是否vector为 4,那么你就有了中间名。如果大小为 3,则不需要。

于 2013-10-06T16:00:30.577 回答