So far I am able to open a txt file and store them as variables.
My txt file looks like this
Tim, 24, Male
I have been able to store them as variables such as name, age, gender
This is my code
ifstream inputfiles ("test.txt");
if(!inputfiles.is_open())
{
}
else
{
while(inputfiles >> name >> age >> gender)
{
cout << name << "\n";
cout << age << "\n";
cout << gender << "\n";
}
However, my code doesn't store the values as variables when my txt file looks like this...
Tim
24
Male
How do I modify my code such that it can read my file line by line and store it in its variables?
If I am right, You want to store it like:
Tim 24 Male
John 25 Male
Use a class
class data
{
public:
char name[10],gen;
int age;
void getdata()
{
cout<<"Enter Name";
gets(name);
cout<<Enter age";
cin>>age;
cout<<"enter gender";
cin>>gen;
}
void putdata()//use cout statements here
{
//put cout statements
}
};
Now in your main function,use write functon
fstream f;
f.open("YourFile.txt",ios::in|ios::out);
data r;
for(i=0;i<10;i++)
{
r.getdata();
f.write((char*)&r,sizeof(r));
}
Remember,always use read function to print the database values if you used write.
f.seekg(0,ios::beg);
while(!f.eof())
{
f.read((char*)&r,sizeof(r));
}
If you want to store the text as it is without conversion...use put function.
Related
So basically all this program does is read in the data into the array of structs of student_type and all the print_students functions does is output the data i get mostly the correct output but i also get random huge numbers.The file data contains the following info and my code is below how do i fix my output?
Smith
John
123456
3.4
J
1750.4
302
Fairmont St NW
Washington
DC
20059
Smitty
Frank
78910
2.7
F
1940.7
302
Sixth St SW
Washington
DC
20059
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
struct Address_type
{
int street_no;
string street_name;
string city;
string state;
int zip;
};
struct student_type
{
string lname;
string fname;
int ID;
float GPA;
char classification;
float account_balance;
Address_type student_address;
};
void print_students(student_type[]); // prototypein
int main()
{
ifstream myfile;
student_type students[5];
myfile.open("infile.txt");
string name1, name2, name3;
for (int i = 0; i < 2; i++) {
myfile >> students[i].lname;
myfile >> students[i].fname;
myfile >> students[i].ID;
myfile >> students[i].GPA;
myfile >> students[i].classification;
myfile >> students[i].account_balance;
myfile >> students[i].student_address.street_no;
myfile >> name1 >> name2 >> name3;
students[i].student_address.street_name = name1 + " " + name2 + " " + name3;
myfile >> students[i].student_address.city;
myfile >> students[i].student_address.state;
myfile >> students[i].student_address.zip;
print_students(students);
}
myfile.close();
}
void print_students(student_type students[])
{
for (int i = 0; i < 2; i++) {
cout << students[i].lname << endl;;
cout<< students[i].fname<<endl;
cout<< students[i].ID<<endl;
cout<< students[i].GPA<<endl;
cout<< students[i].classification<<endl;
cout<< students[i].account_balance<<endl;
cout<< students[i].student_address.street_no<<endl;
cout<<students[i].student_address.street_name<<endl;
cout << students[i].student_address.city << endl;
cout << students[i].student_address.state << endl;
cout << students[i].student_address.zip << endl;
}
}
It looks like you're printing all of your student data on the first iteration of the loop. You should hold off until you've loaded all your data.
Additionally, in C++ it's important to use the Standard Library containers and do your best to avoid C-style fixed-length arrays in situations like this where you're reading in from a file of unknown length.
That is use this:
std::vector<student_type> students;
This can be added to with things like push_back on a properly composed student_type record.
Then you can pass that through by reference to any function that needs it, like print_students for example. Right now, for whatever reason, you just assume that there will be three entries in that array (of length five?) and go ahead and dump it out even if it wasn't populated.
I am having a tough time figuring out the process of reading text files into the program. Down in the get_answer_key_array, I am trying to read and put only the top line of the text file into an array.
The text file looks something like this:
ABDBCBDBABABCBABCB
Bob Bobby adcad abcbd bacb
Every text file tested in this program will have the answer key on the first line. Every line after the first line will have the persons first name, space, last name, space, grades and missing grades will be replaced by a "-" when I get to it.
I am currently working on obtaining the first line and putting it into the answer key array.
I know that once I am done with the first line I can put the persons first name, last name, and answers into three separate parallel arrays. I am having trouble coming up with the right way to check for that first new line so I can get the answer key.
Alright so now I have changed my get_answer_key_array to obtain all of the arrays I will need. Currently I am trying to get the top line (the answer key) into the first array of answer_key[]. I have tried to implement the getline function but am trying to figure out how to only get the top line. Is it possible to keep my eof() loop yet stop at the first endline to transferthe data of the first line into the array? Also my
answer_key[i] = key; needs changed to something else I bet!
I should also mention once I figure out how to get the top line into an array, I want to use this process to get the rest of the data (names and answers) into their own separate arrays via the following workflow:
in_stream >> first_name[i] >> last_name[i] >> answers[i];
while(!in_stream.eof() ) {
i++;
in_stream >> first_name[i] >> last_name[i] >> answers[i];
}
in_stream.close();
START OF PROGRAM BELOW
void get_input_file(ifstream &in_stream); //gets the text file name from the user
void get_arrays(ifstream &in_stream, int answer_key[], string first_name[], string last_name[], int answers[], int &count); //brings the data from text file into all of the parallel arrays
//void score_grader(int &target, string first_name[], string last_name[], int answers[], int &count, int &score);
//void letter_grade(int &score, int &letter_grade);
//void student_report(int &target, string first_name[], string last_name[], int answers []);
int main()
{
ifstream in_stream;
int answer_key[30], count = 0, score = 0; //initializing the answer key array up to 30 answers
string first_name[20]; //initializing the first name array
string last_name[20]; //initializing the last name array
int answers[30]; //initializing the answers array
cout << "Welcome to the Test Grader." << endl; //welcome message
get_input_file(in_stream); //function call to get the file name
get_arrays(in_stream, answer_key, first_name, last_name, answers, count); //function call to create the arrays
}
void get_input_file(ifstream &in_stream) {
string file_name; //initializing the file name string
do {
cout << "Enter the file name you would like to import the data from: " << endl; //asks user to input name of file
cin >> file_name; //user types name of file
in_stream.open(file_name.c_str()); //program opens the stream
if(in_stream.fail()) {
cout << "Error finding file, try again.\n"; //if failed, asks user for file name again
continue; //continues back to the do loop
}
break;
} while(true);
cout << "File Obtained: " << file_name << endl; //alerts user of file success with printed name
}
void get_arrays(ifstream &in_stream, int answer_key[], string first_name[], string last_name[], int answers[],
int &count) {
int i = 0;
string key; //This will be the storage variable for the first line of text file
if (in_stream.is_open() ) { //if the stream is open
getline(in_stream, key);
cout << "Testing: " << key << endl;
while(!in_stream.eof() ) {
i++;
in_stream >> first_name[i] >> last_name[i] >> answers[i];
}
}
cout << first_name[1] << " " << last_name[1] << " " << answers[1] << endl;
in_stream.close();
}
You can simply read the first line this way
void get_answer_key_array(ifstream &in_stream, char *answer_key, int &count) {
in_stream >> answer_key;
count = strlen(answer_key);
}
The answer_key array must be of type char.
And the endline character is '\n' not '/n'
when i run this code everything goes fine when writing , but when i press 2 to read it goes well and read everything just fine but when it it finishes reading the file (show function) it pops up a problem says " Unhandled exception at 0x5DF9CCC8 " with break , continue options .
from my searching i think the problem comes from a pointer points to Null , but i don't know how to resolve it .
here is the code
class person{
public :
string name;
int id ;
int age ;
void person :: show();
void person :: add_menue();
void person :: insert_data();
void person :: show_data();
};
person personobject;
void person :: add_menue()
{
cout << "Please Enter Name ID Age :" << endl;
cin >> name >> id >> age ;
}
ofstream file;
void person::show()
{
cout<<"Age => "<<age<<endl;
cout<<"Name => "<<name<<endl;
cout<<"ID => "<<id<<endl;
}
void person :: insert_data()
{
ofstream file;
file.open("binary.dat",ios::app| ios::binary);
personobject.add_menue();
file.write((char*)&personobject, sizeof(personobject));
file.close();
}
void person :: show_data()
{
ifstream file;
file.open("binary.dat",ios::in| ios::binary);
if(!file)
{
cout<<"File not Found";
}
else
{
file.read((char*)&personobject, sizeof(personobject));
while(!file.eof())
{
personobject.show();
cout<<"Press Any Key....For Next Record"<<endl;
getchar();
file.read((char*)&personobject, sizeof(personobject));
}
}
file.close();
}
void main ()
{
int choice;
cout << "1 - to write \n2 - to read" << endl;
cin >> choice;
if (choice==1)
{
person f;
f.insert_data();
}
if (choice==2)
{
person a;
a.show_data();
system ("pause");
}
}
Because you are using a string object instead of a plain character array, you can't just type cast the whole class to a char* and write it to the file (which in itself is a poor way of doing it. What if you changed around the order of the parameters and tried loading an older file?).
In your insert_data function, write each variable individually instead of casting the entire class. You could write the age and id first and you know that would take up 8 bytes, so whatever is remaining is the size of the name which can be loaded back into the string object in your read_data function.
I know that parsing questions similar to this are asked a lot here, but after having searched for a while, I couldn't find an answer that helped me so hopefully I'm not asking something that has been answered a million times before.
I have a text file that looks like this:
1 14 100
3 34 200
2 78 120
The first number is an ID number, the second is an Age and the third number is a Weight. (These are arbitrary descriptions) I also have a struct that looks like this:
struct myData{
int ID;
int age;
int weight;
};
After creating an array of myData structs, how do I iterate through the text so that eventually I end up with each element of each line of the text file in one index of the array? For example, after populating the array with the elements of the text file, I should be able to say
cout << myData[0].ID << ", " << myData[0].age << ", " << myData[0].weight << "\n";
and it should print out "1, 14, 100" and it should print out "3, 78, 120" if the index was 2 in the line of code above. I've tried looking for example of others using getLine() or get() and things like that but I can't seem to get the hang of it. I hope I included enough information about my question so it can be easily answered by the wizards on this site. Thanks in advance!
How about something like this:
struct myData
{
int ID;
int age;
int weight;
// Add constructor, so we can create instances with the data
myData(int i, int a, int w)
: ID(i), age(a), weight(w)
{}
};
std::vector<myData> input;
std::ifstream file("input.txt");
// Read input from file
int id, age, weight;
while (file >> id >> age >> weight)
{
// Add a new instance in our vector
input.emplace_back(id, age, weight);
// Skip over the newline, so next input happens on next line
std::ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
// Close the file after use
file.close();
// Print all loaded data
for (auto data : input)
{
cout << "ID: " << data.ID << ", age: " << data.age << ", weight: " << data.weight << '\n';
}
You could use the include file :
#include <fstream>
and simply do something similar
std::ifstream infile("file.txt");
int a, b, c;
while (infile >> a >> b >> c)
{
// process (a,b,c)
}
don't forget to close the stream.
Open the file and go through it to read all lines:
//Opening File
FILE *trace;
trace=fopen("//path//to//yourfile","r");
// Read the file
myData list[N];
int count=0;
while(!feof(trace)){
fscanf(trace,"%d %d %d\n", &myData[count].ID, &myData[count].age, &myData[count].weight);
count++;
}
// now you have an array of size N go through it and print all
for(int i=0; i<count; i++)
printf("%d %d %d\n", myData[i].ID, myData[i].age, myData[i].weight);
i am having difficulty understanding how to pass a file into a function.
i have a file with 20 names and 20 test scores that needs to be read by a function. the function will then assign the names and scores to a structure called student.
my question is how would i write a function call with the appropriate parameters. ? to make my function read the data in the file. thanks.
CODE
// ask user for student file
cout << "Enter the name of the file for the student data to be read for input" << endl;
cout << " (Note: The file and path cannot contain spaces)" << endl;
cout << endl;
cin >> inFileName;
inFile.open(inFileName);
cout << endl;
// FUNCTION CALL how do i set this up properly?
ReadStudentData(inFile, student, numStudents );
void ReadStudentData(ifstream& infile, StudentType student[], int& numStudents)
{
int index = 0;
string lastName, firstName;
int testScore;
while ((index < numStudents) &&
(infile >> lastName >> firstName >> testScore))
{
if (testScore >= 0 && testScore <= 100)
{
student[index].studentName = lastName + ", " + firstName;
student[index].testScore = testScore;
index++;
}
}
numStudents = index;
}
The way you pass an ifstream into the function is perfectly fine.
I suspect that the problem lies in the way you are managing your array of StudentType and its size (numStudents). I would recommend changing your code to use an std::vector instead of a raw array. In general, you should always prefer vectors over arrays unless you have a really good reason to use an array.
vectors can grow to accommodate more data and keep track of their size, so you don't have to.
Also, it's a good idea for functions to return objects rather than modify objects passed through the parameter list.
#include <vector>
using namespace std;
vector<StudentType> ReadStudentData(ifstream& infile) {
vector<StudentType> students;
string lastName, firstName;
int testScore;
while (infile >> lastName >> firstName >> testScore) {
if (testScore >= 0 && testScore <= 100) {
StudentType student;
student.studentName = lastName + ", " + firstName;
student.testScore = testScore;
students.push_back(student);
}
}
return students;
}
// call the function
vector<StudentType> students = ReadStudentData(infile);
// or if you have a C++11 compiler
auto students = ReadStudentData(infile);
// use students.size() to determine how many students were read
The reference to the file object seems to be fine, but the array of StudentType objects maybe wrong.
Try this:
void ReadStudentData(ifstream& infile,
std::vector<StudentType>& vecStudents,
int& numStudents)