samedi 1 janvier 2022

C++ How do I get user input to open a file as a struct? [closed]

Hi I am new to C++ and I have decided to work on a text based game to review what I have learned from class. So what I want the code to do is take user input and read the user input file (like a text document for example.) I have recieved errors that are commented in the code, and I am not sure how to go about them. For example filename is undefined, even though I make it equal to the string sfilename.

Thank you for any and all help it's appreciated as this is quite literally confusing me.

Code:

#include <iostream>
#include <string>
#include <fstream>

using namespace std;

string sfilename = filename; /*filename is recieving an error 
E0020 */
sfilename = filename; /* sfilename is recieving error E0077, 
filename has E0020. */

const int SIZE = 1;
void debugPrint();
void loadData();

struct Records {
string firstname;
string secondname;
float test1mark;
float midtestmark;
float annualmark;
}record[SIZE];

int main()
{
std::cout << "Input file name" << endl;
std::cin >> sfilename;

ifstream in(filename); // Same error as the first two.

loadData();
debugPrint();
}

void debugPrint()
{
for (int i = 0; i < SIZE; i++) 
{
std::cout << record[i].firstname << " " << endl;
std::cout << record[i].secondname << " " << endl;
std::cout << record[i].test1mark << " " << endl;
std::cout << record[i].midtestmark << " " << endl;
std::cout << record[i].annualmark << " " << endl;
}
system("PAUSE");
}


void loadData()
{
for (int i = 0; i < SIZE; i++)
{
if (!in)
{
cerr << "File can't be opened!" << endl;
system("PAUSE");
}
in >> record[i].firstname >> record[i].secondname
>> record[i].test1mark >> record[i].midtestmark >> 
record[i].annualmark;
}
}

Aucun commentaire:

Enregistrer un commentaire