【发布时间】:2021-02-07 17:49:27
【问题描述】:
我对编码和 C++ 世界很陌生。我的任务是从具有不同值行的 .txt 文档中获取数字。我需要对每一行进行错误检查,以确保文件格式正确。我希望创建一个可以重用的类来进行这些检查。我,即:
- 从第一行获取数据
- 检查数据是否符合条件(在这种情况下,它必须是 1 或 0,稍后我将不得不根据此值应用不同的操作)
- 根据结果在主文件中触发 true / false if 语句。
Main.cpp
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <functional>
#include "ErrorSwitch.h"
using namespace std;
//Set pointer of 'file' to beginning line of 'num'
fstream& GotoLine(fstream& file, unsigned int num) {
file.seekg(ios::beg);
//Loop through file
for (int i = 0; i < num - 1; ++i) {
file.ignore(numeric_limits<streamsize>::max(), '\n');
}
return file;
}
int main() {
fstream file("file1.txt");
//Check Line 1
GotoLine(file, 1);
//Get Input from First Line & Convert to int
string line1;
file >> line1;
int inpu = stoi(line1);
//Error Check
ErrorSwitch checkOne;
checkOne.input = inpu;
checkOne.errorCheck();
if (checkOne == true) { //I can't seem to get this to work as a boolean check
//Do code here
}
else if (checkOne == false) {
//Do code here
}
}
ErrorSwitch.h
#pragma once
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <functional>
using namespace std;
class ErrorSwitch
{
public:
int input;
bool errorCheck() {
switch (input) {
case 0:
return true;
break;
case 1:
return true;
break;
default:
return false;
}
}
};
有人可以看看这个并帮助我了解如何从这个类函数中获取返回值。 谢谢!
【问题讨论】: