检查输入的文件是否有任何错误
checking to see if any mistakes with an inputted file
我写这段代码是为了打开一个文件并将所有内容存储到全局字符数组组中 [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 文件?
相关文章:
- 类和构造函数中的函数根本不起作用,并且不返回任何错误
- boost::p rogram_options 在指定意外的位置参数时不报告任何错误
- Antlr cpp 运行时 任何错误的指针转换?
- 我可以使用 try catch 语句来捕获任何错误而不是具体错误吗?
- 为什么 C++ 中的分号在插入代码开头时不显示任何错误?
- 如何修复任何错误
- 为什么<<低;和 cout<<v.begin;单独给出错误,但 cout <<(lower.begin());没有给出任何错误,并使代码易于编译
- 我是否需要处理以下代码中的任何错误情况?
- 我的代码在构建时没有任何错误,但无法正常工作
- 由于错误,c ++代码无法在Visual Studios上运行,但不显示任何错误
- ROS2 COLCON构建未在Windows中显示任何错误消息
- 如何调试 gRPC 服务器崩溃而没有任何错误
- 尝试使用类,但未打印任何内容.不会生成任何错误.我错过了什么吗?
- 代码没有任何错误,但什么也不在命令提示中
- GTK图像突然不会刷新任何错误或警告
- STL 中是否有任何错误代码异常
- 用“ strcpy”在2D数组中删除(字符)的一行(字符)时是否存在任何错误
- Oracle ODBC 插入失败,没有任何错误诊断
- 检查输入的文件是否有任何错误
- 带有绝对路径的LoadLibrary返回不正确的HMODULE,没有任何错误