打开文本文件并读取一个带有空格的字符串,然后将两个独立的int放入一个结构中

Opening text file and reading a string with whitespace then 2 seperate ints into a struct

本文关键字:一个 两个 独立 结构 然后 int 空格 文件 文本 读取 字符串      更新时间:2023-10-16

我有一个程序正在启动,并且遇到了早期的障碍。这个程序打开一个包含篮球信息的.txt文件。.txt中的第一个数字是(游戏数组的)大小,然后下一行是名称,其下有客场和主场比分。程序应将所有信息存储到新创建的结构Gameinfo游戏数组中。.txt文件的示例

3
SD Lancers
33   55
ND Cats
34   67
SD Big Horn
67   68

程序得到了大小并动态地正确分配,但它没有得到其余的。我的循环内部一定不正确吗?我顶部的cout没有为名称[0].name提供任何内容。我想我没有正确理解getline?如有任何帮助,我们将不胜感激!谢谢另外,请忽略间距。我从来没有把它们格式化写在这里。

代码:

#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
#include <cctype>
#include <stdlib.h>
using namespace std;

struct GameInfo
{
   string name;
   int home;
   int away;
};
void testpara(ifstream& in,struct GameInfo * & games, int & size);

int main()
{
 int size;
 GameInfo * games;
 ifstream in;
 in.open ("games.txt"); //Here is my problem
 if (!in)
    {
       cout<<"Could not open file";
    }
      testpara(in,games, size);
      in.close();
      cout << "size of games is: " << size << endl;
      cout<<games[1].name<<endl;
  return 0;
 }

  void testpara(ifstream& in,struct GameInfo * & games, int & size)
  {
     int test;
     int count = 0;
     in>>size; //trying to get the first number for the size

     // dynamically allocate games array
     games = new GameInfo [size];

    while(count<size && !in.eof())
    {
      getline(in,games[count].name);
      in>>games[count].away>>games[count].home;
      count++;
    }

   return;
   }

我认为另一种方法可能是利用运算符重载和标准容器来创建更安全、更"c++风格"的代码。在我看来,我们期望的格式更加清晰。您应该注意的另一件事是,您的代码存在内存泄漏(games从未被删除),使用vector是避免这种风险的第一步。

例如:

#include <iostream>
#include <string>
#include <sstream>
#include <vector>
struct GameInfo
{
    std::string name;
    int home;
    int away;
    friend std::istream &operator>>(std::istream &is, GameInfo &g);
    friend std::ostream &operator<<(std::ostream &os, GameInfo &g);
};
std::istream &operator>>(std::istream &is, GameInfo &g) {
    std::getline(is, g.name);
    is >> g.home;
    is >> g.away;
    is.ignore();
    return is;
}
std::ostream &operator<<(std::ostream &os, GameInfo &g) {
    os << "Name: " << g.name << "n" << g.home << " " << g.away << std::endl;
    return os;
}

int main()
{
    std::string str = "3nSD Lancersn33   55nND Catsn34   67nSD Big Hornn67   68n";
    std::cout << str;
    std::istringstream stream(str); // you could use ifstream instead
    size_t size(0);
    stream >> size; // not really nescesasry with vectors but still...
    stream.ignore();
    std::vector<GameInfo> gv;
    for (unsigned int i = 0; i<size; ++i){
        GameInfo g;
        stream >> g;
        gv.push_back(g);
    }
    std::cout << "n-----------------n";
    for (auto& el : gv)
    {
        std::cout << el << "n-----------------n";
    }
    return 0;
}

(coliru)

相关文章: