I'm fairly new to C++ and have no idea where to start with this or if its even possible, but i'm trying to check to see if length, width, radius, etc are actually doubles and if they are not return 0.
int main() {
ifstream inFile;
ofstream outFile;
string in;
double length, width, tLength = 0, tWidth = 0, areaRec, tAreaRec = 0, parameter, tParameter = 0;
double radius, tRadius = 0, areaCirc, tAreaCirc = 0, circumference, tCircumference = 0;
double savings, tSavings = 0;
int people = 0, age, tAge = 0;
string name1, name2;
inFile.open("inData_with_error.txt");
outFile.open("outData_Normal.txt");
outFile << fixed << showpoint << setprecision(2);
if (!inFile) {
cout << "ERROR: Unable to open file!" << endl;
inFile.close();
}
else {
cout << "Caculating..." << endl;
while (inFile >> length >> width >> radius >> name1 >> name2 >> age >> savings) {
cout << length << ", " << width << ", " << radius << ", " << name1 << ", " << name2 << ", " << age << ", " << savings << endl;
tLength = tLength + length;
tWidth = tWidth + width;
parameter = length * 2 + width * 2;
areaRec = length * width;
tParameter = tParameter + parameter;
tAreaRec = tAreaRec + areaRec;
tRadius = tRadius + radius;
areaCirc = pow(radius, 2) * PI;
circumference = (radius * 2) * PI;
tAreaCirc = tAreaCirc + areaCirc;
tCircumference = tCircumference + circumference;
people = people + 1;
tAge = tAge + age;
tSavings = tSavings + savings;
}
}
cout << "Done" << endl;
outFile << "Rectangle:" << endl << "Total length = " << tLength << ", " << "Total width = " << tWidth << ", " << "Total area = " << tAreaRec << ", " << "Total parameter = " << tParameter << endl << endl
<< "Circle:" << endl << "Total radius = " << tRadius << ", " << "Total area = " << tAreaCirc << ", " << "Total circumference = " << tCircumference << endl << endl
<< "Person: " << endl << "Total number of persons = " << people << endl << "Total age = " << tAge << endl << "Total savings = " << tSavings << endl;
inFile.close();
outFile.close();
system("pause");
return 0;
}
For example if my data with error is the below i want to catch the char and strings and return a 0 but have no idea how to tackle this question. Can someone lead me into the right direction?
10.45 aaaa
13.78
Jake Melon 45
7600
128 76.9
;
Mike Sander 23
800
15.9 43
w
David James i
87000.54
After the end of the while loop, you can add a test to check to whether the while loop got terminated due to EOF or due to an error in reading the data.
while (inFile >> length >> width >> radius >> name1 >> name2 >> age >> savings) { ... }
if ( inFile.eof() )
{
// No errors in reading data
}
else
{
// Error in reading data.
// Deal with error
}
Related
I'm a fairly new to c++. I'm trying to create a very basic calculator and the results I'm getting are completely wrong. I've come to a standstill after 2 hours of trying everything in my knowledge. What am I doing wrong?
#include <iostream>
using namespace std;
int main()
{
int a = 0.0;
int b = 0.0;
float sum = 'a' + 'b';
float diff = 'a' - 'b';
float prod = 'a' * 'b';
float quot = 'a' / 'b';
float rem = 'a' % 'b';
//Input
cout << "Enter a number: " << endl;
cin >> a;
cout << "Enter another number: " << endl;
cin >> b;
cout << a << " + " << b << " = " << sum <<endl;
cout << a << " - " << b << " = " << diff <<endl;
cout << a << " / " << b << " = " << quot <<endl;
cout << a << " * " << b << " = " << prod <<endl;
cout << a << " % " << b << " = " << rem <<endl;
return 0;
}
you are calculating with character literals. 'a' is not the same as a here.
remove the quotes when calculating, but add them when you print the actual literal "a"
float sum = 'a' + 'b';
You are calculating the ASCII value of the character "a" (which is 65) with the ASCII value of "b" (which is 66)
It should be
float sum = a + b;
instead.
When you print the values, you did the reverse:
cout << a << " + " << b << " = " << sum <<endl;
You want it to be
cout << "a" << " + " << "b" << " = " << sum <<endl;
instead. You want to print characters for the equation and only a number for the result.
You also calculate the values of a and b before they have an actual value.
You should put the calculation after you enter them.
Fixed, by moving the calculations after the input; and by using variables, not literals.
#include <iostream>
using namespace std;
int main()
{
int a = 0.0;
int b = 0.0;
//Input
cout << "Enter a number: " << endl;
cin >> a;
cout << "Enter another number: " << endl;
cin >> b;
float sum = a + b;
float diff = a - b;
float prod = a * b;
float quot = a / b;
float rem = a % b;
cout << a << " + " << b << " = " << sum <<endl;
cout << a << " - " << b << " = " << diff <<endl;
cout << a << " / " << b << " = " << quot <<endl;
cout << a << " * " << b << " = " << prod <<endl;
cout << a << " % " << b << " = " << rem <<endl;
return 0;
}
I'm trying to make a football tournament in C++, in which the user inputs the name of the teams(8 teams) and then each team has to play with the other one 1 time. Firstly, I don't know how to read the team names, I mean I tried to use .getline or just cin of a char array, but then I need to put the teams into the matrix and after the final game my program should print the table. So there's the first question: how to read the names and basically make the program think they are numbers or does it work with just with names, no need to use int? And then the users inputs the result for every game, but here comes the hard part. After all the results have been introduced, the matrix rotates cyclic and then the result stored in the variables(you will see in code victory/losses) overwrites themselves, so at the end, I cannot print the right table. So that's the second question: How can I make them store to the right 'team' while they rotate? Sorry if I didn't quite explain very well how it works, hope you understand it. Cheers!
// FOOTBALL TOURNAMENT
int map[2][4];
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 4; j++) {
cout << "map[" << i << "][" << j << "]= ";
cin >> map[i][j];
}
}
cout << "The map looks like this:" << endl;
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 4; j++) {
cout << map[i][j] << " ";
}
cout << endl;
}
map[0][0] = 1;
int temp = 0, temp2 = 0, temp3 = 0, temp4 = 0, temp5 = 0, temp6 = 0;
int a, b, c, d, e, f, g, h, round = 0;
int victory_m00(0), losses_m10(0), victory_m10(0), losses_m00(0), victory_m01(0), losses_m11(0), victory_m11(0), losses_m01(0);
int victory_m02(0), losses_m12(0), victory_m12(0), losses_m02(0), victory_m03(0), losses_m13(0), victory_m13(0), losses_m03(0);
do
{
// Insert result for every game
cout << "Enter the result of the first game between " << map[0][0] << " vs. " << map[1][0] << endl;
cin >> a >> b;
if (a > b) {
victory_m00++;
losses_m10++;
}
else if (a < b)
{
victory_m10++;
losses_m00++;
}
cout << "Enter the result of the first game between: " << map[0][1] << " vs. " << map[1][1] << endl;
cin >> c >> d;
if (c > d) {
victory_m01++;
losses_m11++;
}
else if (c < d)
{
victory_m11++;
losses_m01++;
}
cout << "Enter the result of the first game between: " << map[0][2] << " vs. " << map[1][2] << endl;
cin >> e >> f;
if (e > f) {
victory_m02++;
losses_m12++;
}
else if (e < f)
{
victory_m12++;
losses_m02++;
}
cout << "Enter the result of the first game between: " << map[0][3] << " vs. " << map[1][3] << endl;
cin >> g >> h;
if (g > h) {
victory_m03++;
losses_m13++;
}
else if (g < h)
{
victory_m13++;
losses_m03++;
}
round++;
// Map switching
temp = map[1][0];
map[1][0] = map[0][1];
temp2 = map[1][1];
map[1][1] = temp;
temp3 = map[1][2];
map[1][2] = temp2;
temp4 = map[1][3];
map[1][3] = temp3;
temp5 = map[0][3];
map[0][3] = temp4;
temp6 = map[0][2];
map[0][2] = temp5;
map[0][1] = temp6;
// Table calculating and printing ~ also this has to be outside the loop (but at first i wanted to print the table after every 'round'
cout << "This is how the table looks like after the " << round << " round: \n";
cout << map[0][0] << " has: " << victory_m00 << " victory(-ies) and " << losses_m00 << " loss-es!\n";
cout << map[0][1] << " has: " << victory_m01 << " victory(-ies) and " << losses_m01 << " loss-es!\n";
cout << map[0][2] << " has: " << victory_m02 << " victory(-ies) and " << losses_m02 << " loss-es!\n";
cout << map[0][3] << " has: " << victory_m03 << " victory(-ies) and " << losses_m03 << " loss-es!\n";
cout << map[1][0] << " has: " << victory_m10 << " victory(-ies) and " << losses_m10 << " loss-es!\n";
cout << map[1][1] << " has: " << victory_m11 << " victory(-ies) and " << losses_m11 << " loss-es!\n";
cout << map[1][2] << " has: " << victory_m12 << " victory(-ies) and " << losses_m12 << " loss-es!\n";
cout << map[1][3] << " has: " << victory_m13 << " victory(-ies) and " << losses_m13 << " loss-es!\n";
cout << endl;
cout << endl;
} while (map[0][1] != 2);
```
I have a file that includes this information:
Bev Powers
3
76 81 73
Chris Buroughs
5
88 90 79 81 84
Brent Mylus
2
79 81
I have a count controlled loop that will do the first 3 lines and use the information correctly but I am struggling with a loop that will reuse the the loop until all the information is displayed from the file regardless of how many golfers with matches are on the file. I am asking for pointers in the right direction, any assistance would be appreciated.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
ifstream inScores;
string filename;
string name;
int loopCount, matchScore;
int count = 1;
float mean = 0;
float adder = 0;
int main()
{
cout << endl << "Enter the golfer's filename: ";
getline(cin,filename);
cout << endl;
inScores.open(filename.c_str());
if(!inScores)
{
cout << "** " << filename << " does not exist. Please ";
cout << "check the spelling and rerun ";
cout << "the program with an existing golfer file. ** " << endl << endl;
return 1;
}
getline(inScores,name);
inScores >> loopCount;
cout << name << " has " << loopCount << " matches with scores of" << endl << endl;
inScores >> matchScore;
while (count <= loopCount)
{
cout << "Match " << count << ": " << matchScore << endl;
adder = adder + matchScore;
adder = adder + matchScore;
inScores >> matchScore;
count++;
}
cout << endl;
int(mean) = .5 + (adder / loopCount);
cout << "The mean score is " << mean << endl << endl;
inScores.close();
return 0;
}
As stated using loops will be necessary to get what you want. Also since the getline and extraction return false if they fail you can use them for the test in the loop:
ifstream inScores;
string filename;
string name;
int loopCount , matchScore;
int count = 1;
float mean = 0;
float adder = 0;
int main()
{
cout << endl << "Enter the golfer's filename: ";
getline( cin , filename );
cout << '\n';
inScores.open( filename );
if ( !inScores )
{
cout << "** " << filename << " does not exist. Please ";
cout << "check the spelling and rerun ";
cout << "the program with an existing golfer file. ** " << "\n\n";
return 1;
}
while ( getline( inScores , name ) )
{
if ( inScores >> loopCount )
{
cout << name << " has " << loopCount << " matches with scores of" << "\n\n";
}
else
{
cout << "File read error";
return 1;
}
for ( int count = 1; count <= loopCount; count++ )
{
if ( inScores >> matchScore )
{
cout << "Match " << count << ": " << matchScore << '\n';
adder = adder + matchScore;
}
else
{
cout << "File read error";
return 1;
}
}
}
cout << '\n';
int( mean ) = .5 + ( adder / loopCount );
cout << "The mean score is " << mean << "\n\n";
inScores.close();
return 0;
}
I have an assignment for school in which the goal is to read data from a text file, and output calculations made with the info. I've gotten the inputing and outputting mostly down, but our prof wants us to include error checking aswell. I've done error checking for strings, and now im working on ints/doubles. The only issue is when i try to use the sample error input file he provided, my while loop dosen't fire at all.
bool isWord(string s)
{
for (int i = 0; i < s.length(); ++i)
{
if (::isdigit(s[i])){
return false;
}
}
return true;
}
int main()
{
ifstream inData;
ofstream outData;
inData.open("inData.txt");
outData.open("outData.txt");
//check for Error
if (inData.fail()){
cout << "Error opening file!" << endl;
exit(1);
}
if (outData.fail()){
cout << "Error opening file!" << endl;
exit(1);
}
double rWidth;
double rLength;
double cRad;
double number = 0;
string fName;
string lName;
string word;
int age;
int i = 0;
int savings;
int count = 0;
int people = 0;
int tAge = 0;
int tSavings = 0;
string names[256];
double tLength = 0;
double tWidth = 0;
double tArea = 0;
double perimeter = 0;
double tRad = 0;
double tCarea = 0;
double tCirc = 0;
while(inData >> rWidth >> rLength >> cRad >> fName >> lName >> age >> savings){
cout << rWidth << " " << rLength << " " << cRad << " " << fName << " " << lName << " " << age << " " << savings << "\n";
stringstream fNameStream(fName);
stringstream lNameStream(lName);
while (fNameStream >> word)
{
if (isWord(fName))
{
names[count++] = word;
}
else
{
names[count++] = "John";
}
}
while (lNameStream >> word)
{
if (isWord(lName))
{
names[count++] = word;
}
else
{
names[count++] = "Doe";
}
}
istringstream widthStream(rWidth);
while (widthStream >> number)
{
if (widthStream >> number)
{
widthStream >> rWidth;
}
else
{
rWidth = 0.0;
}
}
tLength = tLength + rLength;
tWidth = tWidth + rWidth;
perimeter = perimeter + (2*(rWidth+rLength));
tArea = tArea + (rWidth*rLength);
tRad = tRad + cRad;
tCarea = tCarea + pow(cRad, 2) * M_PI;
tCirc = tCirc + (2*M_PI*cRad);
tAge = tAge + age;
tSavings = tSavings + savings;
}
cout << tLength << "\n";
cout << tWidth << "\n";
cout << perimeter << "\n";
cout << tArea << "\n";
cout << tCarea << "\n";
cout << tCirc << "\n";
cout << tAge << "\n";
cout << tSavings < "\n";
cout << count << "\n";
while (i < count)
{
cout << names[i] << " ";
i++;
}
outData << "Rectangle: \n";
outData << "The total length= " << tLength << ", width= " << tWidth << ", area= " << tArea << "\n";
outData << "Perimeter= " << perimeter << "\n\n";
outData << "Circle:\n";
outData << "The total radius= " << tRad << ", area= " << tCarea << ", circumference= " << tCirc << "\n\n";
outData << "People:\n" << "Total number of people= " << count << "\n" << "Total Age= " << tAge << "\nTotal Savings= " << tSavings;
inData.close();
outData.close();
system("pause");
return 0;
}
Hopfully thats formatted correctly.
The program runs fine and dandy when i use:
10.45 8.76
13.78
Jake Melon 45
7600
128 76.9
11
Mike Sander 56
800
15.9 43
6400
David James 32
87000.54
But when i use:
10.45 aaaa
13.78
Jake Melon 45
7600
128 76.9
;
Mike Sander 23
800
15.9 43
w
David James i
87000.54
My main while loop (where I read data) doesn't fire for some reason, and all of my values remain at 0. Your help will be greatly appreciated! And I'm sorry for such a long block of text.
Error recovery is difficult and there are no standard methods (think about how your compiler recovers from a syntax error).
You will need an outer loop for your while loop. You'll want to come up with a design that will help you resynchronize on the input format. Again, not an easy task.
A simple method is to count the text lines and display the text line where the failure existed and end the program. From that you can display more information, such as the field that was in error. Some programmers assume the worst that once an error is found the remaining data can't be trusted.
I recommend putting in place a simple error announcement and safely terminate (clean up, flush to disk, etc.). Work on getting the remainder of your program working correctly, then come up with better error handling strategies.
I am in a second-year computer science class and we are learning C++.
The assignment is to write a text file and calculate totals and averages based on the text file's data.
This is what my text file looks like:
Angela Langston Maya Malcolm Total Average
Algebra 64.5 56.7 67.4 90.0
CS1 88.6 77.0 55.3 89.4
English 91.3 67.4 89.0 100.0
Science 100.0 89.4 80.2 91.4
Average
I was doing just fine until I compiled and debugged. My program will not print the second line of my text file correctly. It prints out:
-107374176.0 -107374176.0 -107374176.0 -107374176.0 -429496704.0 -107374176.0
instead of the data I have stored in the text file.
Please help. I'll provide any additional information that is needed to solve this problem. Also, just a reminder, I am a beginner C++ user.
Update:
Here's the code:
#include <iostream>
#include <string>
#include <iomanip>
#include <fstream>
using namespace std;
void student_heading();
void report_heading();
float average_calc(float);
int main()
{
cout << fixed << showpoint << setprecision(1);
string name1, name2, name3, name4;
string title1, title2;
string class1, class2, class3, class4, title3;
string fecha;
float algebra1, cs1, english1, science1;
float algebra2, cs2, english2, science2;
float algebra3, cs3, english3, science3;
float algebra4, cs4, english4, science4;
float algebra_total;
algebra_total = 0;
float cs_total = 0;
cs_total = 0;
float english_total = 0;
english_total = 0;
float science_total;
science_total = 0;
float algebra_avg, cs_avg, english_avg, science_avg;
float angela_avg, langston_avg, maya_avg, malcolm_avg;
float angela_total, langston_total, maya_total, malcolm_total;
angela_total = algebra1 + cs1 + english1 + science1;
langston_total = algebra2 + cs2 + english2 + science2;
maya_total = algebra3 + cs3 + english3 + science3;
malcolm_total = algebra4 + cs4 + english4 + science4;
angela_avg = average_calc(angela_total);
langston_avg = average_calc(langston_total);
maya_avg = average_calc(maya_total);
malcolm_avg = average_calc(malcolm_total);
student_heading();
cout << "What is today's date? (Example: May 1, 1996 = 05/01/1996): " << endl;
cin >> fecha;
cout << "DATE:" << fecha << "*************************************************** Page 1" << endl;
report_heading();
ifstream inData;
inData.open("infile.txt");
inData >> name1 >> name2 >> name3 >> name4 >> title1 >> title2;
cout << " " << name1 << " " << name2 << " " << name3 << " " << name4 << " " << title1 << " " << title2 << endl;
inData >> class1 >> algebra1 >> algebra2 >> algebra3 >> algebra4 >> algebra_total >> algebra_avg;
algebra_total = algebra1 + algebra2 + algebra3 + algebra4;
algebra_avg = average_calc(algebra_total);
cout << class1 << " " << algebra1 << " " << algebra2 << " " << algebra3 << " " << algebra4 << " " << algebra_total << " " << algebra_avg << endl;
inData >> class2 >> cs1 >> cs2 >> cs3 >> cs4 >> cs_total >> cs_avg;
cs_total = cs1 + cs2 + cs3 + cs4;
cs_avg = average_calc(cs_total);
cout << class2 << " " << cs1 << " " << cs2 << " " << cs3 << " " << cs4 << " " << cs_total << " " << cs_avg << endl;
inData >> class3 >> english1 >> english2 >> english3 >> english4 >> english_total >> english_avg;
english_total = english1 + english2 + english3 + english4;
english_avg = average_calc(english_total);
cout << class3 << english1 << english2 << english3 << english4 << english_total << english_avg;
inData >> class4 >> science1 >> science2 >> science3 >> science4 >> science_total >> science_avg;
science_total = science1 + science2 + science3 + science4;
science_avg = average_calc(science_total);
cout << class4 << science1 << science2 << science3 << science4 << science_total << science_avg;
inData >> title3;
cout << title3 << angela_avg << langston_avg << maya_avg << malcolm_avg << endl;
inData.close();
return 0;
}
void report_heading()
{
cout << "********************SMALL COLLEGE GRADE REPORT*******************" << endl;
}
void student_heading()
{
cout << "*******************" << endl;
cout << "Student" << endl;
cout << "ID" << endl;
cout << "SYCS-135 Computer Science I" << endl;
cout << "Assignment 5" << endl;
cout << "September 24, 2015" << endl;
cout << "******************" << endl;
}
float average_calc(float total_value)
{
float average;
average = total_value / 4;
return average;
This line
inData >> class1 >> algebra1 >> algebra2 >> algebra3 >> algebra4 >> algebra_total >> algebra_avg;
attempts to read the string "CS1" into algebra_total, which causes the stream to fail. Either don't attempt to read those numbers, or fix your text file to something like
Angela Langston Maya Malcolm Total Average
Algebra 64.5 56.7 67.4 90.0 0 0
CS1 88.6 77.0 55.3 89.4 0 0
English 91.3 67.4 89.0 100.0 0 0
Science 100.0 89.4 80.2 91.4 0 0
Average