c++ - 从输入文件中读取

标签 c++

我在读取输入文件时遇到问题。 输入文件看起来像这样

莱昂内尔·梅西 -10 43

费尔南多·托雷斯 9 -29

克里斯蒂亚诺罗纳尔多 7 31

韦恩鲁尼 10 37

内马尔 17 29

伊涅斯塔 8 32

罗宾范佩西 19 20

莱昂内尔·梅西 10 43

哈维埃尔南德斯 6 36

梅苏特·厄齐尔 10 38

迪迪埃·德罗巴 10 35

费尔南多·托雷斯 9 29

卡卡 10 17

问题是我不能使用 getline 函数,因为我想将名称存储到单个变量中以存储到数组中,第一个数字存储到一个变量中,第二个数字存储到另一个变量中。我也尝试过使用 peek 功能,但我从来没有学过,所以我没有成功。 如果有人知道如何读取到名称末尾并将其存储到单个变量中,将不胜感激。

这是我从输入文件中读取代码时的样子

while(!fin.eof())
    {

     fin >> first >> last >> num >> point;

     if (num > 0 && point > 0)
     {
             list[i].firstname = first;
             list[i].lastname = last;
             list[i].number = num;
             list[i].points = point;
             i++;
     }
     else if (num < 0 || point < 0)
     {
             reject[j].firstname = first;
             reject[j].lastname = last;
             reject[j].number = num;
             reject[j].points = point;
             j++;
     }

    }

如果输入有名字和姓氏,这将非常有效。我知道问题是 在 fin >> first >> last >> num >> point;

但我不确定如何将第一个和最后一个(可能还有中间)放在一起

最佳答案

您可以使用 std::getline 提取行,将行解析为空格分隔的单词的 std::vector。然后你知道 words.size() - 2 的单词是名字的一部分。例如:

std::fstream in("in.txt");
std::string line;

// Extract each line from the file
while (std::getline(in, line)) {
  std::istringstream line_stream(line);

  // Now parse line_stream into a vector of words
  std::vector<std::string> words(std::istream_iterator<std::string>(line_stream),
                                 (std::istream_iterator<std::string>()));

  int name_word_count = words.size() - 2;
  if (name_word_count > 0) {
    // Concatenate the first name_word_count words into a name string
    // and parse the last two words as integers
  }
}

关于c++ - 从输入文件中读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16203702/

相关文章:

c++ - 从 C++ 中的字符串中获取每个单独的单词

c++ - boost asio tcp socket 1.70 不向后兼容

c++ - for 循环不终止

c++ - 是否可以实现自动全局转换?

C++ 析构函数约定

C++ 包括 .cpp : avoiding multiple definition errors

c++ - C++ 中简单 std::map 迭代的意外输出

c++ - Boost Geometry:计算 vector 差

c++ - undefined reference C++

c++ - 声明一个 int 变量