I'm a very novice programmer, and I'm trying to make a program that reads a txt file containing the names of 5 students (first names only) as well as four exam scores for each student. I'm trying to read the names into an array called students, then read the scores into 4 separate arrays named test1, test2, test3, test4, then display it from the monitor. The file looks like this:
Steve 78 65 82 73
Shawn 87 90 79 82
Annie 92 90 89 96
Carol 72 65 65 60
Kathy 34 50 45 20
I'm having a very hard time with breaking up the arrays and organizing them. Can someone help me? Please keep in mind I'm very novice, so I don't know a large amount about programming.
This is my code thus far:
#include <cstdlib>
#include <iostream>
#include <string>
#include <fstream>
#include <iomanip>
#include <ctime>
#define over2 "\t\t"
#define over3 "\t\t\t"
#define over4 "\t\t\t\t"
#define down5 "\n\n\n\n\n"
using namespace std;
int main(int argc, char *argv[])
{
ifstream inputFile;
//Constant for max string size
const int SIZE = 5;
//Constant for the scores
string names[SIZE], fileName, line, test1[SIZE], test2[SIZE], test3[SIZE], test4[SIZE];
//input section, user enters their file name
cout << down5 << down5 << over2 << "Please enter your file name: ";
cin >> fileName;
system("CLS");
//open the file containing the responses
inputFile.open(fileName.c_str());
cout << endl;
//kicks you out if file isn't found
if (inputFile)
{
for(int i = 0; i < SIZE; i++)
{
getline(inputFile, line);
names[i] = line;
getline(inputFile, line);
test1[i] = line;
getline(inputFile, line);
test2[i] = line;
getline(inputFile, line);
test3[i] = line;
getline(inputFile, line);
test4[i] = line;
}
inputFile.close();
}
cout << down5 << over3 << "Student\tTest1\tTest2\tTest3\tTest4\n";
cout << over3 << "-------\t-----\t-----\t-----\t-----\n";
for(int i = 0; i < SIZE; i++)
{
cout << over3 << names[i] << endl;
cout << over3 << test1[i] << endl;
cout << over3 << test2[i] << endl;
cout << over3 << test3[i] << endl;
cout << over3 << test4[i] << endl;
}
return 0;
}
Let's look at the structure of the file you're trying to read:
Steve 78 65 82 73
Shawn 87 90 79 82
Annie 92 90 89 96
Carol 72 65 65 60
Kathy 34 50 45 20
The format of the data can be described as follows:
Each line represents a single "record".
Each "record" contains multiple columns.
Columns are separated by whitespace.
You're currently using getline() for every column:
for(int i = 0; i < SIZE; i++)
{
getline(inputFile, line);
names[i] = line;
getline(inputFile, line);
test1[i] = line;
getline(inputFile, line);
test2[i] = line;
getline(inputFile, line);
test3[i] = line;
getline(inputFile, line);
test4[i] = line;
}
...whereas you actually want to read in a single line for each record and split it up:
for (int i = 0; i < SIZE; i++)
{
string line;
size_t start = 0;
// For each line, attempt to read 5 columns:
getline(inputFile, line);
names[i] = get_column(line, start);
test1[i] = get_column(line, start);
test2[i] = get_column(line, start);
test3[i] = get_column(line, start);
test4[i] = get_column(line, start);
}
Here's a modified version of your original code, which splits up each line as described above:
#include <cctype>
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
static string get_column(string line, size_t &pos)
{
size_t len = 0;
// Skip any leading whitespace characters.
while (isspace(line.c_str()[pos])) { ++pos; }
// Count the number of non-whitespace characters that follow.
while (!isspace(line.c_str()[pos+len]) && line.c_str()[pos+len]) { ++len; }
// Extract those characters as a new string.
string result = line.substr(pos, len);
// Update the "start" position (for the next time this function is called).
pos += len;
// Return the string.
return result;
}
int main()
{
const int SIZE = 5;
string names[SIZE], test1[SIZE], test2[SIZE], test3[SIZE], test4[SIZE];
// Ask the user to enter a file name.
cout << "Please enter your file name: ";
string fileName;
cin >> fileName;
// Open the file and read the data.
ifstream inputFile(fileName.c_str());
if (!inputFile.is_open()) { return 0; }
for (int i = 0; i < SIZE; i++)
{
string line;
size_t start = 0;
// For each line, attempt to read 5 columns:
getline(inputFile, line);
names[i] = get_column(line, start);
test1[i] = get_column(line, start);
test2[i] = get_column(line, start);
test3[i] = get_column(line, start);
test4[i] = get_column(line, start);
}
inputFile.close();
// Display the data.
cout << "Student\tTest1\tTest2\tTest3\tTest4" << endl;
cout << "-------\t-----\t-----\t-----\t-----" << endl;
for(int i = 0; i < SIZE; i++)
{
cout << names[i] << "\t";
cout << test1[i] << "\t";
cout << test2[i] << "\t";
cout << test3[i] << "\t";
cout << test4[i] << endl;
}
}
Running the program produces the following output:
Please enter your file name: textfile.txt
Student Test1 Test2 Test3 Test4
------- ----- ----- ----- -----
Steve 78 65 82 73
Shawn 87 90 79 82
Annie 92 90 89 96
Carol 72 65 65 60
Kathy 34 50 45 20
Note that the get_column() function handles multiple spaces or too-short lines, so that this file:
Steve 78 65 82 73
Shawn 87 90
Annie 92 90 89 96
Carol 72
Kathy 34 50 45 20
...produces the following output:
Please enter your file name: textfile.txt
Student Test1 Test2 Test3 Test4
------- ----- ----- ----- -----
Steve 78 65 82 73
Shawn 87 90
Annie 92 90 89 96
Carol 72
Kathy 34 50 45 20
The previous answer is overthinking the problem.
You can use your input file stream to retrieve 'formatted input' (that is, input you know to be in a format such as 'string' then 'int', 'int', 'int', 'int') with the >> operator.
string name;
int score[4];
ifstream mf;
mf.open("score.txt");
// Get name string.
mf >> name;
// Get four score values into an array.
mf >> score[0] >> score[1] >> score[2] >> score[3];
And then:
cout << name;
cout << score[0];
cout << score[1];
cout << score[2];
cout << score[3];
Related
for my csc 102 assignment, I need to create a class to hold a student's grades and name. Then output that information to a text file. The grades and name are both read from an input file. I got it to succesfully run one instance of student. However, I do not know how to make the next student object read from the next line.
the input file is in this format:
Jonathan Blythe 87 76 79 88
Jessica Blake 87 79 58 86
Jonathan Lee 88 86 69 100
Joseph Blake 78 89 50 69
My first Student object Student a; reads the correct line. However, when I call the function again for another Student object Student b;, it still reads the first line, and overwrites the output file. I thought if I didn't close the file until the end of main that it may read correctly. I will show the class header file, and the implementation file for Student below.
#include "Student.h"
Student::Student() {
cout << "Default Constructor" << endl;
}
void Student::getscores() {
ifstream infile;
infile.open("input.txt");
infile >> firstName >> lastName;
for (int i = 0; i <= 3; i++) {
infile >> scores[i];
}
infile.close();
}
void Student::getaverage() {
average = 0;
for (int i = 0; i < 4; i++) {
average = average + scores[i];
}
average = average / 4;
}
void Student::print()const {
ofstream outfile;
outfile.open("output.txt");
outfile << firstName << " " << lastName << endl;
cout << firstName << " " << lastName << endl;
for (int i = 0; i <= 3; i++) {
cout << scores[i] << " ";
outfile << scores[i] << " ";
}
cout << endl;
outfile << endl;
cout << "Average Score: " << average << endl;
outfile << "Average Score" << average << endl;
cout << "Letter Grade: " << grade << endl;
outfile << "Letter Grade: " << grade << endl;
//outfile.close();
}
void Student::getletter() {
if (average >= 90)
grade = 'A';
else if (average >= 80 && average < 90)
grade = 'B';
else if (average >= 70 && average < 80)
grade = 'C';
else if (average >= 60 && average < 70)
grade = 'D';
else if (average < 60)
grade = 'F';
}
Student::~Student() {
}
and
#pragma once
#include<iostream>
#include<string>
#include <fstream>
using namespace std;
class Student
{
string lastName;
string firstName;
int scores[4] = { 0,0,0,0 };
int average = 0;
char grade = 'n';
public:
Student();
Student(string, string, int, int, int, int, char);
~Student();
void getscores();
void getaverage();
void getletter();
void print()const;
};
How do I read incrementally to the next line everytime a function is called?
One option is to pass the input stream as an argument to the function.
You should read the input.txt line by line, for each line you need to parse to get the firstName, lastName, scores then use them to create a new object of Student class (you need some changes of Student class to create object from name, set scores, etc.)
I suggest the code skeleton is something like below:
char line[128] = {0,};
ifstream infile;
infile.open("input.txt");
if (!infile.is_open()) {
return;
}
while (infile.getline(line, sizeof(line) - 1)) { // read content of next line then store into line variable
// parse content of line to get firstName, lastName, scores
...
// create new object of Student class from firstName, lastName, scores you got
...
// clear content in line
memset(line, '\0', sizeof(line));
}
this is my code, when i am reading the lines which must be stored in the class, its reading one line and storing the value of next line, I am unable to identify my mistake in the code. Please help me to correct it. the task is to skip the lines that has sentences and read the lines which has data abd store it in the class variables.
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <stack>
#include <string>
using namespace std;
class data_Read
{
public:
/* timestamp */
double time;
/*state of the signal 1 or 2*/
unsigned int state;
/*ID in hexadecimal and converted to decimal*/
std::string ID;
/* Received or transmitted message */
std::string status;
/* Message type */
std::string type;
/* byte length */
unsigned int byte_lent;
/* CAN Message */
std::string message_1;
std::string message_2;
std::string message_3;
std::string message_4;
std::string message_5;
std::string message_6;
std::string message_7;
std::string message_8;
std::string type1;
std::string type2;
std::string type3;
std::string type4;
std::string type5;
std::string type6;
std::string type7;
std::string type8;
std::string type9;
};
int main()
{
std::ifstream ifs("datatrace.txt");
data_Read data;
std::string line;
while (!ifs.eof())
{
start:
std::getline(ifs, line);
std::cout << line << std::endl;
if (!isspace(line[0]))
{
goto start;
}
std::size_t space = line.find(" ", 0);
if (space == 0)
{
int i;
for (i = 0; i <= 15; i++)
{
if (isalpha(line[i]))
{
goto start;
}
}
ifs >> data.time >> data.state >> data.ID >> data.status >> data.type >> data.byte_lent >> data.CAN_message_1 >> data.CAN_message_2 >> data.CAN_message_3 >> data.CAN_message_4 >> data.CAN_message_5 >> data.CAN_message_6;
ifs >> data.CAN_message_7 >> data.CAN_message_8 >> data.type1 >> data.type2 >> data.type3 >> data.type4 >> data.type5 >> data.type6 >> data.type7>> data.type8 >> data.type9;
cout << data.time << "\t" << data.state << "\t" << data.ID << "\t" << data.status << "\t" << data.type << "\t" << data.byte_lent << "\t" << data.CAN_message_1 << "\t" << data.CAN_message_2 << "\t" << data.CAN_message_3 << "\t";
cout << data.CAN_message_4 << "\t"<< data.CAN_message_5 << "\t"<< data.CAN_message_6 << "\t" << data.CAN_message_7 << "\t"<< data.CAN_message_8 << "\t"<< data.type1 << "\t"<< data.type2 << "\t"<< data.type3 << "\t"<< data.type4 << "\t"<< data.type5 << "\t" << data.type6 << "\t"<< data.type7 << "\t"<< data.type8 << "\t"<< data.type9 << endl;
}
}
ifs.close();
return 0;
}
and the text file contain
date Fri Sep 1 02:11:40.195 pm 2017
base hex timestamps absolute
internal events logged
// version 9.0.0
Begin Triggerblock Fri Sep 1 02:11:40.195 pm 2017
0.000000 Start of measurement
0.002893 1 201 Rx d 8 06 0D 00 B0 89 00 0D E7 Length = 227925 BitCount = 118 ID = 513
0.003133 1 280 Rx d 8 1B 0C 7C F1 E8 75 39 67 Length = 221910 BitCount = 115 ID = 640
0.006981 CAN 1 Status:chip status error active
0.006981 CAN 2 Status:chip status error active
0.007123 1 244 Rx d 8 7B 01 00 08 80 80 C0 00 Length = 233925 BitCount = 121 ID = 580
0.007148 2 B2 Rx d 8 C0 13 9A 13 D8 13 C0 13 Length = 221910 BitCount = 115 ID = 178
0.007359 1 246 Rx d 8 55 01 00 49 50 B6 7A 89 Length = 217925 BitCount = 113 ID = 582
0.007394 2 86 Rx d 8 62 00 2A 20 01 84 02 00 Length = 225925 BitCount = 117 ID = 134
the final answer
while (std::getline(file, line))
{
std::istringstream iss(line);
std::size_t space = line.find(" ", 0);
if (!isspace(line[0]))
{
iss.clear();
}
else
{
int i;
for (i = 0; i <= 12; i++)
{
if (isalpha(line[i]))
{
iss.clear();
goto start;
}
}
iss >> data.time >> data.state >> data.ID >> data.status >> data.type >> data.byte_lent >> data.CAN_message_1 >> data.CAN_message_2 >> data.CAN_message_3 >> data.CAN_message_4 >> data.CAN_message_5 >> data.CAN_message_6;
iss >> data.CAN_message_7 >> data.CAN_message_8 >> data.type1 >> data.type2 >> data.type3 >> data.type4 >> data.type5 >> data.type6 >> data.type7 >> data.type8 >> data.type9;
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
ifstream fin ("data1.txt");
int ID;
string name;
int test1, test2, test3;
char answer;
cin >> answer;
while (answer = 'Y')
{
fin >> ID;
getline(fin, name);
cout << name << endl;
fin >> test1, test2, test3;
cout << ID << endl;
cout << test1 << "\t" << test2 << "\t" << test3 << "\t";
cin >> answer;
}
}
http://postimg.org/image/fjknavue9/ (Image showing the error)
It showing this error.
For some reason it is just reading the first ID. And then garbage.
This is the TXT file
211692
Ahmed, Marco
66 88 99
240885
ATamimi, Trevone
30 60 90
281393
Choudhury, Jacob
45 55 65
272760
De la Cruz, Edward
79 89 49
199593
Edwards, Faraj
90 56 96
256109
Edwards, Bill
93 94 95
246779
Gallimore, Christian
22 88 66
270081
Lopez, Luis
100 100 100
114757
Mora, Sam
63 78 88
270079
Moses, Samuel
48 95 99
193280
Perez, Albert
97 57 0
252830
Rivas, Jonathan
44 56 76
252830
Robinson, Albert
85 87 89
276895
Miranda, Michael
82 72 62
280515
Robinson, Iris
64 78 91
Program wwill only read the first id, but nothing else, yet it will display whats given, if not garbage. With knowing the solution or understanding, what is going wrong, it can help me in another program that deals with the same logic.
As #Akshat Mahajan mentioned two problems in your code, I fixed and tested them.
One more thing is needed. You should add a line fin.ignore() to ignore the the new line after taking an integer from file.
Here is the working code:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
ifstream fin ("data1.txt");
int ID;
string name;
int test1, test2, test3;
char answer;
cin >> answer;
while (answer == 'Y')
{
fin >> ID;
fin.ignore();
getline(fin, name);
cout << name << endl;
fin >> test1>> test2>> test3;
cout << ID << endl;
cout << test1 << "\t" << test2 << "\t" << test3 << "\t";
cin >> answer;
}
}
However, you have done some bad practice in your code. Instead of using answer == 'Y' as the condition of while, try something like fin>>ID.
If you choose to use getline for everything, you can change your code a little bit as below.
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
using namespace std;
int main()
{
ifstream fin ("data1.txt");
int ID;
string name, line;
int test1, test2, test3;
char answer;
cin >> answer;
while (answer == 'Y')
{
getline (fin, line);
ID = stoi(line);
getline(fin, name);
cout << name << endl;
getline(fin, line);
stringstream ss(line);
ss >> test1 >> test2 >> test3;
cout << ID << endl;
cout << test1 << "\t" << test2 << "\t" << test3 << "\t";
cin >> answer;
}
}
I'm writing a program that takes a text file with results of an ad campaign and need to find the average rating of the campaign for 4 different demographics. I think I have it all figured out just struggling with getting the data from the file and into char and int variables. Do I need to read it all as strings and then convert or can I read them into those variables?
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
using namespace std;
int main(){
//declare vars
ifstream fileIn;
string path;
string name;
char yn;
int age;
double rating;
double rate1 = 0;
double rate1Count = 0;
double avg1 = 0;
double rate2 = 0;
double rate2Count = 0;
double avg2 = 0;
double rate3 = 0;
double rate3Count = 0;
double avg3 = 0;
double rate4 = 0;
double rate4Count = 0;
double avg4 = 0;
double totalAvg = 0;
cout << fixed << showpoint << setprecision(2);
// prompt user
cout << "Please enter a path to the text file with results: ";
// get path
cin >> path;
cout << endl;
// open a file for input
fileIn.open(path);
// error message for bad file
if (!fileIn.is_open()){
cout << "Unable to open file." << endl;
getchar();
getchar();
return 0;
}
// read and echo to screen
cout << ifstream(path);
// restore the file
fileIn.clear();
fileIn.seekg(0);
cout << endl << endl;
// get average for demos
while (!fileIn.eof){
fileIn >> name;
fileIn >> yn;
fileIn >> age;
fileIn >> rating;
if (yn != 121 && age < 18){
rate1 += rating;
rate1Count++;
}
if (yn == 121 && age < 18){
rate2 += rating;
rate2Count++;
}
if (yn != 121 && age >= 18){
rate3 += rating;
rate3Count++;
}
if (yn == 121 && age >= 18){
rate4 += rating;
rate4Count++;
}
}
avg1 = rate1 / rate1Count;
avg2 = rate2 / rate2Count;
avg3 = rate3 / rate3Count;
avg4 = rate4 / rate4Count;
cout << yn << age << rating;
// pause and exit
getchar();
getchar();
return 0;
}
The text file
Bailey Y 16 68
Harrison N 17 71
Grant Y 20 75
Peterson N 21 69
Hsu Y 20 79
Bowles Y 15 75
Anderson N 33 64
Nguyen N 16 68
Sharp N 14 75
Jones Y 29 75
McMillan N 19 8
Gabriel N 20 62
Ditch the cout << ifstream(path); ... fileIn.seekg(0); - that's all unhelpful.
For input, use:
while (fileIn >> name >> yn >> age >> rating)
{
...
That will exit when there's some problem getting the input - whether due to invalid characters for the type (e.g. letters when reading a number), or end-of-file.
Do I need to read it all as strings and then convert or can I read them into those variables?
As above, you don't need to, but you can get better quality input validation and error messages for the user if you get each complete line as a string then attempt to parse out the values:
std::string line;
for (int line_num = 1; getline(fileIn, line); ++line_num)
{
std::istringstream iss(line);
if (iss >> name >> yn >> age >> rating >> std::ws &&
iss.eof())
...use the values...
else
std::cerr << "bad input on line " << line_num
<< " '" << line << "'\n";
// could exit or throw if desired...
}
I've never posted here before but I'm really stuck so I thought i'd give it a try. I've been working on this code for a while, The aim is to input a few students with their marks and to output them into tables with averages and totals. I was given a file like this:
15
Albert Einstein 52 67 63
Steve Abrew 90 86 90 93
David Nagasake 100 85 93 89
Mike Black 81 87 81 85
Andrew Van Den 90 82 95 87
Joanne Dong Nguyen 84 80 95 91
Chris Walljasper 86 100 96 89
Fred Albert 70 68
Dennis Dudley 74 79 77 81
Leo Rice 95
Fred Flintstone 73 81 78 74
Frances Dupre 82 76 79
Dave Light 89 76 91 83
Hua Tran Du 91 81 87 94
Sarah Trapp 83 98
my problem is that when I am inputting the names the program crashes after Fred Flinstone, I know its not a problem with the formatting of the next name (Frances Dupre) because when i moved him up the list it read it fine.
I have located where the program is crashing with 'cerr' outputting at different stages of the read process and it crashes when it is trying to read in Frances's marks.
a1main.cpp
#include <iostream>
#include "student.h"
using namespace std;
int main()
{
int numStds;
cin >> numStds;
cerr << endl << "Num Stds: " << numStds << endl;
Student std[numStds+1];
for(int i = 0; i <= numStds; i++)
{
std[i].readData();
std[i].printStudent();
}
// delete [] std;
return 0;
}
student.h
#include <iostream>
using namespace std;
class Student {
private:
char* name;
int mark[4];
int num;
public:
Student();
~Student();
void readData();
void printStudent();
float getTotal();
float getAverage();
};
student.cpp
#include <iostream>
#include <cstring>
#include <cctype>
#include "student.h"
using namespace std;
Student::Student()
{
name = new char;
mark[0] = 0;
mark[1] = 0;
mark[2] = 0;
mark[3] = 0;
num = 0;
}
Student::~Student()
{
// Doesn't work?
// delete name;
}
void Student::readData()
{
int l = 0;
// Reading the Name
cin >> name; // Read in the first name
l = strlen(name); // get the strlength
name[l] = ' '; // Putting a space between the first and last name
cin >> &name[l+1]; // Read in the last name
cerr << endl << "I have read the name!" << endl;
// Checking if there is a third name
if(cin.peek() == ' ')
cin >> ws; // checking and navigating past the whitespace
char next = cin.peek();
if( isalpha(next) ) // Checking whether the next cin is a char
{
l = 0;
l = strlen(name);
name[l] = ' ';
cin >> &name[l+1];
}
cerr << "I've checked for a third name!" << endl;
// Reading in the marks
for(int i = 0; i < 4; i++)
{
// Checks if the next cin is a newline
if (cin.peek() == '\n')
break;
cin >> mark[i];
}
cerr << "I've read in the marks!" << endl;
//cerr << endl << "I have read " << name << "'s marks!" << endl << endl;
for(int m = 0; m < 4; m++)
{
if(mark[m] != 0)
{
num++;
}
}
cerr << "I've incremented num!" << endl << endl;
}
// Function for error checking
void Student::printStudent()
{
cout << endl << "Student Name: " << name << endl;
cout << "Mark 1: " << mark[0] << endl;
cout << "Mark 2: " << mark[1] << endl;
cout << "Mark 3: " << mark[2] << endl;
cout << "Mark 4: " << mark[3] << endl;
cout << "num marks: " << num << endl << endl;
}
float Student::getTotal()
{}
float Student::getAverage()
{}
Can anyone see what i'm doing wrong? thanks :)
You're never allocating memory to store the student names.
In your Student constructor, add this code:
name = new char[100]; // allows names up to 100 characters long
and uncomment this line in the destructor:
delete[] name;
You could also make the code more sophisticated and robust by measuring the name length and allocating the correct size, or use std::string as suggested below.