检查输入的文件是否有任何错误

checking to see if any mistakes with an inputted file

本文关键字:任何 错误 是否 文件 输入 检查      更新时间:2023-10-16

我写这段代码是为了打开一个文件并将所有内容存储到全局字符数组组中 [800]

void readfile(char usrinput[]) // opens text file
{
    char temp;
    ifstream myfile (usrinput);
    int il = 0;
    if (myfile.is_open())
    {
      while (!myfile.eof())
      {
        temp = myfile.get();
        if (myfile.eof())
        {
          break;
        }
        team[il] = temp;
        il++;
      }
      myfile.close
    }       
    else
    {
      cout << "Unable to open file. (Either the file does not exist or is formmated incorrectly)" << endl;
      exit (EXIT_FAILURE);
    }
    cout << endl;
}

用户需要创建一个格式化的输入文件,其中第一列是名称,第二列是双精度,第三列也是双精度。像这样:

Trojans, 0.60, 0.10
Bruins, 0.20, 0.30
Bears, 0.10, 0.10
Trees, 0.10, 0.10
Ducks, 0.10, 0.10
Beavers, 0.30, 0.10
Huskies, 0.20, 0.40
Cougars, 0.10, 0.90

我目前想添加一个检查,如果用户只输入 7 个团队,则退出程序,或者用户输入超过 8 个团队,或双倍数字。

我尝试在另一个函数中使用计数器(计数器 != 8 并且您脱离循环/程序)创建一个 if 语句,我将其拆分为三个不同的数组,但这不起作用。我现在正在尝试在此功能中完成此检查,如果可能的话,有人可以指导我朝着正确的方向前进吗?我感谢所有的帮助,如果我能提供更多信息,让事情变得不那么模糊,请告诉我。

编辑:我们不允许使用向量或字符串

我建议切换到向量而不是数组,并使用getline一次获取一行。 另外,我不确定您如何从代码中的文件返回数据。

伪代码:

void readfile(char usrinput[], std::vector<string>& lines) // opens text file
{
    ifstream myfile (usrinput);
    if (!myfile.good()) {
      cout << "Unable to open file. (Either the file does not exist or is formmated incorrectly)" << endl;
      exit (EXIT_FAILURE);
    }
    std::string line;
    while (myfile.good()) {
      getline(myfile, line);
      lines.push_back(line);
    }
    myfile.close();
    // it would be safer to use a counter in the loop, but this is probably ok
    if (lines.size() != 8) {
      cout << "You need to enter exactly 8 teams in the file, with no blank lines" << endl;
      exit(1);
    }
}

这样称呼它:

std::vector<string> lines;
char usrinput[] = "path/to/file.txt";
readfile(usrinput, lines);
// lines contains the text from the file, one element per line

另外,请查看以下内容: 如何在C++中读取和解析 CSV 文件?