c++ - 读取中间名可选的文件

标签 c++ string file file-io cin

我正在尝试读取格式为

的文件

firstName middleName(optional) lastName petName\n

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

最佳答案

你可以这样做:

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 ...
}

关于c++ - 读取中间名可选的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19210755/

相关文章:

C++ 数组和 make_unique

php - C++ 相当于 PHP 的 pack()

c++ - std::string 的 type_traits 段错误

string - 如何使用递归函数从文本中获取字符串直到第一个空格?

c - while(true) 之前的 printf 消失

c - 为什么会发生堆损坏?

c++ - 为什么我可以在 C 中调用函数而不声明它,但不能在 C++ 中调用?

c - 显示文件大小 [C]

javascript - csv 文件的 d3 检索在 javascript 控制台中返回 Nan

c - 我怎样才能将结构保存在文件中.... C lang