【问题标题】:checking to see if any mistakes with an inputted file检查输入的文件是否有任何错误
【发布时间】:2014-02-22 05:41:58
【问题描述】:

我编写这段代码是为了打开一个文件并将所有内容存储到一个全局字符数组组 [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 语句,在该函数中我将其拆分为三个不同的数组,但这不起作用。我现在正在尝试在此功能中完成此检查,如果可能的话,有人可以指导我朝着正确的方向前进吗?感谢所有帮助,如果我能提供更多信息以使事情变得不那么模糊,请告诉我。

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

【问题讨论】:

    标签: c++ arrays file-io char


    【解决方案1】:

    我建议切换到向量而不是数组,并使用 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
    

    另外,请查看:How can I read and parse CSV files in C++?

    【讨论】:

    • 哦,我的糟糕,我忘了提到我们不允许使用向量
    • 在这种情况下,我建议将行创建为固定大小的 char[] 的 8 元素数组,而不是向量 (char lines[8][100])。然后,在循环中使用计数器,可能类似于for (int i = 0; i &lt; 8 &amp;&amp; myfile.good(); ++i)。另外,请查看 istream::getline (cplusplus.com/reference/istream/istream/getline) 和 strcpy (cplusplus.com/reference/cstring/strcpy)。
    • 是的,我认为这会起作用,我只是不确定如何将它实现到我当前的代码中以将所有内容存储到团队中[il]
    • 一定要用char team[800]吗?就从 CSV 存储数据而言,它几乎是您拥有的最原始的方法。由于您不允许使用向量,我假设您不能使用任何 STL 其他容器,如队列/列表/等。而且由于您不能使用 std::string ,因此您必须使用 char 数组。因此,像我上面描述的二维数组可能是您的最佳选择,因为它在每个元素中只为您提供一行,这可以在您以后需要获取团队名称和号码时简化您的代码。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-12
    • 2014-08-09
    • 2023-03-25
    • 2022-01-01
    • 2013-12-29
    相关资源
    最近更新 更多