So i have a program that reads from a text file and outputs to another text file. Here is the file text (format included) that it reads:
Duckey Donald 85
Goof Goofy 89
Brave Balto 93
Snow Smitn 93
Alice Wonderful 89
Samina Akthar 85
Simba Green 95
Donald Egger 90
Brown Deer 86
Johny Jackson 95
Greg Gupta 75
Samuel Happy 80
Danny Arora 80
Sleepy June 70
Amy Cheng 83
Shelly Malik 95
Chelsea Tomek 95
Angela Clodfelter 95
Allison Nields 95
Lance Norman 88
In the program it adds each of these to a struct within an array; it then calculates the grade and prints.
cout << "Student Name Test Score Grade" << endl;
for (int studentNumber = 0; studentNumber < STUDENT_NUMBER; studentNumber++){
cout << students[studentNumber].studentLName << ", "
<< students[studentNumber].studentFName << " "
<< students[studentNumber].testScore << " "
<< students[studentNumber].grade << endl;
}
The desired output looks like this:
Student Name Test Score Grade
Donald, Duckey 85 B
Goofy, Goof 89 B
Balto, Brave 93 A
Smitn, Snow 93 A
Wonderful, Alice 89 B
Akthar, Samina 85 B
Green, Simba 95 A
Egger, Donald 90 A
Deer, Brown 86 B
Jackson, Johny 95 A
Gupta, Greg 75 C
Happy, Samuel 80 B
Arora, Danny 80 B
June, Sleepy 70 C
Cheng, Amy 83 B
Malik, Shelly 95 A
Tomek, Chelsea 95 A
Clodfelter, Angela 95 A
Nields, Allison 95 A
Norman, Lance 88 B
Highest Test Score: 95
Students having the highest test score:
Green, Simba
Jackson, Johny
Malik, Shelly
Tomek, Chelsea
Clodfelter, Angela
Nields, Allison
So basically my question is this... is there any way for the test score column integers to line up like they do in my above desired output?
SOLUTION
int colWidth = 20;
for (int studentNumber = 0; studentNumber < STUDENT_NUMBER; studentNumber++){
string s = students[studentNumber].studentFName + ", " + students[studentNumber].studentLName;
int size = s.size();
cout << s << std::string(colWidth - size, ' ')
<< students[studentNumber].testScore << " "
<<
You can pad the string manually with spaces like so:
#include <string>
#include <iostream>
int main()
{
std::string first("John");
std::string last("Smith");
std::string full = last + ", " + first;
int colWidth = 20;
std::cout << "12345678901234567890\n"
<< full << std::string(colWidth - full.size(), ' ')
<< "aligned after 20 characters\n";
return 0;
}
Outputs:
12345678901234567890
Smith, John aligned after 20 characters
This will work for left justifying your text, given you calculate the number of characters you print.
For right-justifying, std::setw from <iomanip> works well. Unlike other stream manipulators, std::setw is not sticky, so it will only modify your next immediate output.
#include <string>
#include <iostream>
#include <iomanip>
int main()
{
std::string s("ABCDE");
int colWidth = 20;
std::cout << "12345678901234567890\n";
std::cout << std::setw(colWidth) << s << "\n";
return 0;
}
Prints
12345678901234567890
ABCDE
Putting it all together, I would left justify the first column, and right justify the second and third columns.
#include <string>
#include <iostream>
#include <iomanip>
int main()
{
std::string first("John");
std::string last("Smith");
std::string full = last + ", " + first;
int score = 100;
std::string grade("A");
std::cout << "123456789012345678901234512345\n"
<< full << std::string(20 - full.size(), ' ')
<< std::setw(5) << score
<< std::setw(5) << grade << "\n";
return 0;
}
Prints:
123456789012345678901234512345
Smith, John 100 A
You can change your code like this:
#include <iomanip>
cout << "Student Name Test Score Grade" << endl;
for (int studentNumber = 0; studentNumber < STUDENT_NUMBER; studentNumber++){
cout << setiosflags(ios::left) << setw(29) << setfill(' ')
<< students[studentNumber].studentLName + ", " + students[studentNumber].studentFName
<< setw(8) << students[studentNumber].testScore
<< students[studentNumber].grade << endl;
}
where 29 and 8 are calculated based on your disired output format, you can change it as you needs.
Related
i have this assignment im doing and previously i did an assignment similar and it worked just fine. but now that im doing this second more complex form, its having trouble reading and storing the proper data. when i decided to try the previous source code that worked fine before i sumbitted it, it didnt work now either. im suppose to open a file and store a list of months names in an array of structs along with their high and low temps using a function outside of main, while also using 2 more functions to find the highest and lowest temp which will be output in function main. but with the data not coming out correctly i cant test the other 2 functions. i cant figure out if i have something corrupt somewhere or whats suddenly causing the files input on both programs to suddenly not work properly.
the input file is
January 47 36
February 51 37
March 57 39
April 62 43
May 69 48
June 73 52
July 82 56
August 81 57
September 75 52
October 64 46
November 52 41
December 45 35
the source code i got looks like
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
struct month
{
string monthName;
int highTemp;
int lowTemp;
};
void loadData(ifstream &infile, month Temperatures [], int &size);
month averageHigh(month Temperatures [], int size);
month averageLow(month Temperatures [], int size);
int main ()
{
ifstream inFile;
int length;
month Temperatures[12];
month highMonth, lowMonth;
cout << "This program is designed to take a struct of months and their corresponding \nhigh/low
temperatures "
<< "from an outside file, than calculate which months had the average high and low." <<
endl;
cout << endl;
inFile.open("weather.txt");
loadData(inFile, Temperatures, length);
averageHigh(Temperatures, length);
averageLow(Temperatures, length);
cout << highMonth.monthName << " has the highest temp of " << highMonth.highTemp << endl;
cout << lowMonth.monthName << " has the lowest temp of " << lowMonth.lowTemp << endl;
inFile.close();
return 0;
}
void loadData(ifstream &infile, month Temperatures [], int &size)
{
cout << "The months highs(left) and lows(right) are: " << endl;
for (size = 0; !infile.eof(); size++)
{
infile >> Temperatures[size].monthName >> Temperatures[size].highTemp >>
Temperatures[size].lowTemp;
cout << Temperatures[size].monthName << " " << Temperatures[size].highTemp << " " <<
Temperatures[size].lowTemp << endl;
}
}
month averageHigh(month Temperatures [], int size)
{
int highArray = 0;
for (int array = 1; array < size; array++)
if (Temperatures[highArray].highTemp < Temperatures[array].highTemp)
highArray = array;
return Temperatures[highArray];
}
month averageLow(month Temperatures [], int size)
{
int lowArray = 0;
for (int array = 1; array < size; array++)
if (Temperatures[lowArray].lowTemp < Temperatures[array].lowTemp)
lowArray = array;
return Temperatures[lowArray];
}
but with this the file keeps trying to store the values
4343069 0
0 0
11998488 0
321518481 32761
11993088 0
0 0
4342068 0
11998488 0
321518481 32761
4741664 0
0 0
4746688 0
then it gives random characters like G and pi and 0s.
Here is a cleaner code for you:
#include <algorithm>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
struct Temperature {
string month;
int high;
int low;
};
istream &operator>>(istream &in, Temperature &temp) {
in >> temp.month >> temp.high >> temp.low;
return in;
}
ostream &operator<<(ostream &out, const Temperature &temp) {
out << temp.month << (temp.month.length() > 7 ? "\t" : "\t\t") << temp.high << '\t' << temp.low << endl;
return out;
}
vector<Temperature> getData(ifstream &infile) {
vector<Temperature> vect;
Temperature temp;
while (infile >> temp)
vect.push_back(temp);
return vect;
}
Temperature highest(vector<Temperature> &data) {
return *max_element(data.begin(), data.end(), [](const Temperature &a, const Temperature &b) {
return a.high < b.high;
});
}
Temperature lowest(vector<Temperature> &data) {
return *min_element(data.begin(), data.end(), [](const Temperature &a, const Temperature &b) {
return a.low < b.low;
});
}
int main() {
ifstream infile("weather.txt");
int length;
auto data = getData(infile);
for (auto &i : data)
cout << i;
auto h_T = highest(data), l_T = lowest(data);
cout << endl
<< h_T.month << " has highest temperature of " << h_T.high << endl
<< l_T.month << " has lowest temperature of " << l_T.low << endl
<< endl;
return 0;
}
weather.txt:
January 47 36
February 51 37
March 57 39
April 62 43
May 69 48
June 73 52
July 82 56
August 81 57
September 75 52
October 64 46
November 52 41
December 45 35
Output:
January 47 36
February 51 37
March 57 39
April 62 43
May 69 48
June 73 52
July 82 56
August 81 57
September 75 52
October 64 46
November 52 41
December 45 35
July has highest temperature of 82
December has lowest temperature of 35
I am trying to get this C++ assignment aligned properly. The main goal is to properly read data from a file, which is being done, but the output is not aligned properly.
Somebody has suggested putting all the variables into one string and outputting that row by row, but that seems like I would need to re-write the majority of the program and I'm not completely sure how to do it. I have attached the code and what the output looks like below. Just wondering if there's a better way to keep everything aligned while using setwidth, or another basic alignment method if one exists. By the way, the file's input can change.
while (!PatientsFile.eof()) {
PatientsFile >> firstName;
PatientsFile >> lastName;
PatientsFile >> pulse;
PatientsFile >> respir;
PatientsFile >> oxygen;
PatientsFile >> room;
string name = firstName + ", " + lastName;
//patient info
cout << setw(4) << room << ' ';
cout << name;
//pulse
if (pulse >= 101) {
cout << setw(13) << "High=" << pulse << ' ';
dangerCount++; }
else if (pulse <= 59) {
cout << setw(16) << "Low=" << pulse << ' ';
dangerCount++; }
else {
cout << setw(19) << pulse << ' '; }
//respir
if (respir >= 21) {
cout << setw(5) << "High=" << respir << ' ';
dangerCount++; }
else if (respir <= 10) {
cout << setw(6) << "Low=" << respir << ' ';
dangerCount++; }
else {
cout << setw(7) << respir << ' '; }
//oxygen
if (oxygen >= 101) {
cout << setw(7) << "High=" << oxygen << ' ';
dangerCount++; }
else if (oxygen <= 91) {
cout << setw(5) << "Low=" << oxygen << ' ';
dangerCount++; }
else {
cout << setw(7) << oxygen << ' '; }
//dangerCount
if (dangerCount == 1) {
checkTotal++;
cout << "CHECK\n";}
else if (dangerCount == 2) {
alertTotal++;
cout << "ALERT***\n"; }
else if (dangerCount == 3) {
criticalTotal++;
cout << setw(15) << "CRITICAL****\n"; }
else {
normalTotal++;
cout << endl; }
dangerCount = 0;
}
//display totals
cout << endl << normalTotal << " Normal\n";
cout << alertTotal << " ALERT\n";
cout << checkTotal << " CHECK\n";
cout << criticalTotal << " CRITICAL\n";
Output:
Room Name Pulse Respir Oxygen
-----------------------------------------------------
111 Pete, Moss Low=59 11 Low=91 ALERT***
312 Diana, Canser High=107 Low=10 96 ALERT***
332 Willie, Makit High=123 High=30 94 ALERT***
111 Betty, Wont Low=50 Low=10 Low=90 CRITICAL****
331 Freda, Spirit High=110 High=23 Low=90 CRITICAL****
321 Wilma, Moneylast High=132 18 Low=88 ALERT***
121 Robin, Banks Low=59 20 100 CHECK
122 Charlie, Horse Low=56 15 95 CHECK
121 Eileen, Back Low=45 17 Low=88 ALERT***
222 Eaton, Buggs 79 16 97
222 Summer, Day 60 12 92
231 Bea, Sting 73 High=21 Low=91 ALERT***
311 Anita, Bath High=111 High=33 97 ALERT***
232 April, Showers 61 High=22 93 CHECK
222 Rose, Bush 100 20 100
231 Buster, Leggs 88 High=44 Low=88 ALERT***
221 Barb, Wire 60 12 Low=82 CHECK
322 Jim, Shoos High=101 19 94 CHECK
322 Kris, Mass Low=4 14 99 CHECK
222 Rich, Bright 77 16 92
4 Normal
8 ALERT
6 CHECK
2 CRITICAL
You can try using tab \t in order to align your list correctly.
Here is the link you might want to look at: How many spaces for tab character(\t)?
Otherwise you will have to do
cout << "text" << setw(#) << "text" << setw(#) << endl;
I would advise against this since it just hardcoding set numbers and its tedious because you would have to count and make sure it is matching correctly.
As Xion's answer mentioned, the process of hardcoding the correct value for the for the text to be aligned correctly, is tedious. Furthermore, it might even not be correct at all for a different data set - For example, what would happen if someone had a much larger name than anticipated?
My suggestion is the following: Iterate over the data completely once, and store the maximum width of each field in a separate variable (also storing the data retrieved).
After that, you could then loop once again over the input, and now everything would be correctly aligned, as you would now know the maximum width of each field (including not having the guess the correct spacing for the header column beforehand, which would be ideal).
You could either create objects of this information and store them in a std::vector, or do the same with each separate data field, having a vector for each one.
Why is the program skipping the first line of every new deptnum?
I am trying to read from a file that looks like:
1 Suits 0300 100 092
1 Coats 0200 060 065
1 Shirts 1000 012 013
2 Dresses 0400 060 065
2 Coats 0185 184 200
2 Shoes 0600 040 030
3 Jeans 0200 040 035
3 Shoes 0200 030 034
4 Jeans 0300 042 043
The deptnum is the first column.
And when I write to the other file I get:
Blinn Discount Apparel Company
Inventory Evaluation
10/12/2018
Unit Cost Extended
Quantity Cost Market Cost Market Lower Cost
Mens Dept
Suits 300 100.00 92.00 30000.00 27600.00
Coats 200 60.00 65.00 12000.00 13000.00
Shirts 1000 12.00 13.00 12000.00 13000.00
Total $54000.00 $53600.00 $53600.00
Womens Dept
Coats 185 184.00 200.00 34040.00 37000.00
Shoes 600 40.00 30.00 24000.00 18000.00
Total $112040.00 $108600.00 $108600.00
Girls Dept
Shoes 200 30.00 34.00 6000.00 6800.00
Total $118040.00 $115400.00 $115400.00
Boys Dept
Total $118040.00 $115400.00 $115400.00
Total Inventory $393000.00
It skipped Womens Dept -> Dresses, Girls Dept -> Jeans, and Boys Dept -> Jeans.
Here is my code:
#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;
int main()
{
ifstream inFile;
ofstream outFile;
int x = 1, deptnum, quant,cost,mkt,extcost,extmkt,totalcost = 0,totalmkt = 0,
lowcost,totalInv = 0;
char item [15];
inFile.open("blinn.dat");
outFile.open("blinn.dout");
if (!inFile)
cout <<"\n\t\t Can't open data file: blinn.dat\n";
else {
outFile <<"\n\t Blinn Discount Apparel Company\n";
outFile <<"\t Inventory Evaluation\n";
outFile <<"\t 10/12/2018\n";
outFile <<"\n\t\t\t\t\t\t Unit Cost\t\t\t Extended\n";
outFile <<"\t\t Quantity Cost Market Cost Market Lower Cost";
while (x < 5)
{
if (x == 1)
outFile << "\nMens Dept";
else if (x == 2)
outFile << "\nWomens Dept";
else if (x == 3)
outFile << "\nGirls Dept";
else if (x == 4)
outFile << "\nBoys Dept";
else
break;
while (inFile >> deptnum >> item >> quant >> cost >> mkt)
{
if (deptnum == x){
extcost = quant * cost;
extmkt = quant * mkt;
outFile << left << "\n " << setw(7)<< item << " "
<< right << setw(4)<< quant << " "
<< right << setw(4) << cost << ".00 "
<< right << setw(3) << mkt << ".00 "
<< right << setw(5) << extcost<< ".00 "
<< right << setw(5) << extmkt << ".00";
totalcost += extcost;
totalmkt += extmkt;
if (totalcost > totalmkt)
lowcost = totalmkt;
else
lowcost = totalcost;
}else
break;
}
outFile << right << "\n Total\t\t\t\t\t $" << totalcost << ".00 $"
<< totalmkt << ".00 $"<< lowcost << ".00";
x += 1;
totalInv += lowcost;
}
}
outFile << "\nTotal Inventory\t\t\t\t\t\t $"<< totalInv<< ".00";
inFile.close ();
outFile.close ();
return 0;
}
What is wrong with my logic?
There is a problem with your logic:
if (deptnum == x) {
// do something
}
else {
break;
}
To achieve the else branch, you have already read a line that deptnum != x (the first line of every new deptnum) so at the next iterator, the current line is discarded by the next input line.
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];
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.