#include <fstream>
#include <iostream>
#include <string>
#include <iomanip>
#include <array>
#include <sstream>
using namespace std;
void NumberSummaryList(string);
void Validation(string);
int main()
{
string file = "";
cout << "Hello, what is the name of the number file that you would like to process, please don't forget to include .txt " << "-For Example- data.txt" << endl;
cin >> file;
try
{
ifstream DataIn;
DataIn.open(file);
if (DataIn.is_open() == false)
{
throw 20;
}
}
catch (int e)
{
cout << "An error has occurred with opening the file." << endl;
}
NumberSummaryList(file);
Validation(file);
}
void NumberSummaryList(string file)
{
ifstream DataIn;
DataIn.open(file);
const int NumbersArray = 100;
int numbers[NumbersArray];
int count;
int x;
int min = 0;
int max = 0;
int temp = 0;
float sum = 0;
float avg = 0;
count = 0;
while (!DataIn.eof())
{
DataIn >> numbers[count];
count++;
}
x = count;
DataIn.close();
for (int count = 0; count < x; count++)
{
cout << numbers[count] << "\n";
}
min = numbers[0];
max = numbers[0];
for (int count = 0; count < x; count++)
{
temp = numbers[count];
if (temp < min)
min = temp;
if (temp > max)
max = temp;
}
for (int count = 0; count < x; count++)
{
sum += numbers[count];
}
avg = sum / x;
ofstream OutData;
OutData.open("listsummary.txt");
cout << "The total of numbers read in the data file is " << x << endl;
cout << "The average of all numbers in the data file is " << avg << endl;
cout << "The max value of the data file is " << max << endl;
cout << "The min value of the data file is " << min << endl;
OutData << "The total of numbers read in the data file is " << x << endl;
OutData << "The average of all numbers in the data file is " << avg << endl;
OutData << "The max value of the data file is " << max << endl;
OutData << "The min value of the data file is " << min << endl;
OutData.close();
}
void Validation(string file)
{
ifstream DataInStrings;
DataInStrings.open(file);
int count = 0;
string stringarray[100];
int intarray[100];
int y = 0;
for (int count = 0; count < 100; count++)
{
getline(DataInStrings, stringarray[count]);
if (stringarray[count].length() > 5)
{
cout << "Error Found! The element in position " << count + 1 << " " << stringarray[count] << " is too long. Error Written." << endl;
}
else
{
}
}
for (int count = 0; count < 100; count++)
{
string CopyofArray;
CopyofArray = stringarray[count];
int intcopy = stoi(CopyofArray);
if (intcopy < 0)
{
cout << "Error Found! The element in position " << count + 1 << " " << stringarray[count] << " is negative. Error Written." << endl;
}
else
{
}
}
for (int count = 0; count < 100; count++)
{
cout << stringarray[count] << "\n";
}
string ArrayCopy;
ArrayCopy = stringarray[count];
//if (isalpha(ArrayCopy))
//{
//}
//else
//{
// cout << "Alphabetical characters detected in the file, error written." << endl;
//}
DataInStrings.close();
}
Hey guys. This is a project for class that I am stuck on and struggling with. The goal is to validate some of the data inside of the file I load in, which should be numbers 1-100. My teacher has required me to write out errors if the file contains any alphanumericals, symbols like ? or /, if the length of the element is greater than 5, and if the number is negative.
The program is also supposed to display the contents of the file 1-100, find the max, min, average, and total of numbers read.
I have successfully read in the file, found the max, min, average, and total of numbers read. I also have successfully programmed it to write out errors if a number is too long or if it is negative.
However, my trouble comes whenever the file contains either an alphanumerical or a symbol. The file simply won't load and the program won't function correctly if I try to test out putting a alphanumerical or symbol in the data file.
I tried rewriting the program to use getline at first and read in the strings, and then convert when needed. But it now has an issue of where the program will not compute after an alphanumerical is found.
I am here to ask for advice or some type of direction in the right way. My teacher had us write part of the program first, and then added in the data validation parts which angers me because it jumbles the whole thing up in different places.
I look forward to any... please and thanks guys!
Related
I want to find Maximum numbers from my "numbers.txt" file and amount of negative numbers. And i want to output the Total result to another .txt file and console and the rest to the console only.
Im very new and just cant figure out how to do it.
This is what i have now
a "numbers.txt" file with
-4
53
-5
-3
2
and
#include <iostream>
#include <fstream>
using namespace std;
int main() {
int n = 0;
int sum = 0, total = 0;
fstream file("numbers.txt");
while (file >> n)
{
sum += n;
total++;
}
int average = (float)sum / total;
int AmountOfNumbersAdded = total;
int Highest;
int Negative;
cout << "Total result: " << sum << endl;
cout << "Numbers added: " << AmountOfNumbersAdded << endl;
cout << "Average number: " << average << endl;
cout << "Maxiumum number: " << endl;
cout << "Negative numbers: " << endl;
return 0;
}
i tried to do
float Highest = INT_MIN;
if (Highest < num[i]) {
Highest = num[i];
but it just wouldn't work.
You don't need to store the numbers to find the maximum or the amount of negative numbers, but you need to track them inside the loop, like you're already doing with the sum and the total amount of numbers.
int Highest = INT_MIN;
int Negative = 0;
while (file >> n)
{
sum += n;
total += 1;
if (n < 0)
{
Negative += 1;
}
if (n > Highest)
{
Highest = n;
}
}
float average = (float)sum / total;
Here's what you're looking for.
#include <iostream>
#include <fstream>
int main()
{
int n = 0;
int sum = 0, total = 0;
int highest = 0;
int negatives = 0;
std::fstream file("numbers.txt");
while (file >> n)
{
if (n > highest) highest = n;
if (n < 0) ++negatives;
sum += n;
++total;
}
int average = (float)sum / total;
int AmountOfNumbersAdded = total;
std::cout << "Total result: " << sum << "\n";
std::cout << "Numbers added: " << AmountOfNumbersAdded << "\n";
std::cout << "Average number: " << average << "\n";
std::cout << "Maxiumum number: " << highest << "\n";
std::cout << "Negative numbers: " << negatives << "\n";
file.close();
return 0;
}
As you're new, few advices for you:
Never use using namespace std.
Prefer using "\n" instead of std::endl.
Don't forget to close any files/database after opening them like you did in your code.
Always try to avoid macros.
I created a program to display an average from an array of numbers the user have decided to input. The program asks the user the amount of numbers he / she will input, then they input all positive numbers. The output for the average is always a decimal, how can I only display the whole number without any decimal points. Ex. 12.34 = 12 / 8.98 = 8
#include <iostream>
#include <iomanip>
using namespace std;
void sortingTheScores(double *, int);
void showsTheScoresNumber(double *, int);
double averageForAllScores(double, int);
int main()
{
double *scores;
double total = 0.0;
double average;
int numberOfTestScores;
cout << "How many test scores do you have? ";
cin >> numberOfTestScores;
scores = new double[numberOfTestScores];
if (scores == NULL)
return 0;
for (int count = 0; count < numberOfTestScores; )
{
cout << "Test Score #" << (count + 1) << ": ";
cin >> scores[count];
while (scores[count] <= 0)
{
cout << "Value must be one or greater: " ;
cin >> scores[count];
}
count = count +1;
}
for (int count = 0; count < numberOfTestScores; count++)
{
total += scores[count];
}
sortingTheScores(scores, numberOfTestScores);
cout << "The numbers in set are: \n";
showsTheScoresNumber(scores, numberOfTestScores);
averageForAllScores(total, numberOfTestScores);
cout << fixed << showpoint << setprecision(2);
cout << "Average Score: " << averageForAllScores(total,numberOfTestScores);
return 0;
}
void sortingTheScores (double *array, int size)
{
int sorting;
int theIndex;
double theNumbers;
for (sorting = 0; sorting < (size - 1); sorting++)
{
theIndex = sorting;
theNumbers = array[sorting];
for (int index = sorting + 1; index < size; index++)
{
if (array[index] < theNumbers)
{
theNumbers = array[index];
theIndex = index;
}
}
array[theIndex] = array[sorting];
array[sorting] = theNumbers;
}
}
void showsTheScoresNumber (double *array, int size)
{
for (int count = 0; count < size; count++)
cout << array[count] << " ";
cout << endl;
}
double averageForAllScores(double total, int numberOfTestScores)
{ double average;
average = total / numberOfTestScores;
return average;
}
You can use I/O manipulators here:
#include <iostream>
#include <iomanip>
int main()
{
std::cout << std::setprecision(0) << 1.231321 << '\n';
}
Output:
1
You can do it without using iomanip library:
std::cout.precision(0);
std::cout << 1.231321 << std::endl;
Then you'll simply get:
1
Just you need to use std::cout.precision() which is equivalent to std::setprecision() from iomanip library.
Edit:
The aforementioned solution is okay for smaller floating point values, but if you try something like 1334.231321, the std::cout will result displaying some scientific notation, something like:
1e+03
which is actually odd to read and understand. To solve it, you need std::fixed flag, you may write something like:
std::cout.precision(0), std::cout << std::fixed;
std::cout << 1334.231321 << std::endl;
Then it'll show:
1334
For numbers in a +/-2^31 range you can do:
cout << int(12.34) << " " << int(8.98) << endl;
which produces output
12 8
You may also want to consider rounding to the nearest integers. To do so
add a line
#include <cmath>
then do
cout << int(rint(12.34)) << " " << int(rint(8.98)) << endl;
this gives
12 9
I'm trying to store hexadecimal values into some form of an array from a file then change those numbers to binary. So far the program I wrote is only collects the last value. The file looks something like this. note(a 1 or 0 is before each hex value)
1 408ed4
0 10019d94
0 408ed8
1 10019d88
0 408edc
0 1001322
My code is #include
#include <fstream>
#include <string>
#include <cstdlib>
#include <bitset>
#include <sstream>
#define MAX_ADDRESSES 1000000
using namespace std;
int main(int argc, char **argv) {
//Declare variables
int szL1 = atoi(argv[2]);
int szL2 = atoi(argv[4]);
string type = argv[6]; //Determines the type of cache
//string fileN = argv[7];
int info, i = 1, j = 1; //info is what is read in, i & j are testing variables
string *rd_add = new string[MAX_ADDRESSES]; //set the max string length for what's read
string *wrt_add = new string[MAX_ADDRESSES]; //set the max string length for what's written
int total = 0; //total # of reads/writes
int rds = 0; //base # of reads
int wrt = 0; //base # of writes
int array_size = 1001024;
char *array = new char[array_size];
int position = 0;
ifstream fin("big_trace.txt");//open big trace file********
if (fin.is_open()){
cout << "File opened successfully" << endl;
while (!fin.eof() && position < array_size){
fin.get(array[position]);
position++;
}
array[position - 1] = '\0';
for (int x = 0; array[x] != '\0'; i++){
cout << array[i];
}
}
else{
cout << "File could not be opened" << endl;
}
//check for a power of 2 for szL1
while (1)
{
if (i == szL1)
break;
//Error Message
else if (i > szL1)
{
cout << "Error. sizeL1 must be a power of 2. Please try again." << endl << endl;
return 0;
}
i *= 2;
}
//cout << "size1 " << szL1 << endl;
//check for a power of 2 for szL2
while (1)
{
if (j == szL2)
break;
//Error
else if (j > szL2)
{
cout << "Error. sizeL2 must be a power of 2. Please try again." << endl << endl;
return 0;
}
j *= 2;
}
//cout << "size2 " << szL2 << endl;
//Check to see if szL2 is larger than szL1
if (szL2 <= szL1)
{
cout << "Error. sizeL2 must be larger than sizeL1. Please try again." << endl << endl;
return 0;
}
//Read file contents*****
while (cin >> info) //check this part
{
//If it is a 1, increment read files
if (info == 1)
{
cin >> rd_add[i++];
rds++;
}
else if (info == 0)
{
cin >> wrt_add[j++];
wrt++;
}
else
{
continue;
}
}
total = rds + wrt;
//Print the arguments read
cout << endl << "Input Parameters read:" << endl;
cout << "SizeL1: " << szL1 << endl;
cout << "SizeL2: " << szL2 << endl;
cout << "Type: " << type << endl;
//Print file stats
cout << endl << "Memory References Read from File" << endl;
cout << "Total: " << total << endl;
cout << rds << " Reads" << endl;
cout << wrt << " Writes" << endl;
return 0;
}
If you want to get only the hexadecimal values in a vector and your file is as you said you can just do it as below:
String hexValue, dummy;
Vector<String> hexValueVector;
ifstream fin("big_trace.txt");//open big trace file********
if (fin.is_open()){
cout << "File opened successfully" << endl;
while (!fin.eof()){
fin >> dummy >> hexValue;
hexValueVector.push_back(hexValue);
....//your remaining code
Do not forget to include the Vector library.
#include <vector>
Hope this will help you.
EDITED:
if you need the dummy too you have just to put both values in a structure:
struct myStructure{
String dummy;
String hexValue;
};
and instead of creating a vector of string you create a vector of myStructure:
Vector<myStructure> myStructureVector;
to fill your vector you have just to do this:
myStructure myStructure;
if(fin.is_open()){
...
while (!fin.eof()){
fin >> myStructure.dummy >> myStructure.hexValue;
myStructureVector.push_back(myStructure);
If this solves your problem, please vote for the answer.
About Vector, it is a STL container, if you want more details about it check http://www.cplusplus.com/reference/vector/vector/
This seems simple enough but I'm missing something here to make this code work. What I'm trying to do is print the contents of the two dimensional array in 25 rows and 4 columns with student's num, id, score, and name.
I experimented with something similar to this code when I initialized the array with numbers. But now that I'm reading the data from a file, I've hit a wall and need help.
I tried using the name of the array in the cin object but I got an error message like this:
"assign6.cpp:49:11: error: no match for 'operator>>' (operand types are 'std::ifstream {aka std::basic_ifstream}' and 'const int (*)[4]')"
So I took that out and now the code compiles but I get garbage. Any suggestions? Sorry about not getting back soon. I got caught up in other assignments. I made changes and now the programs works. Here the results.
#include <iostream>
#include <iomanip>
#include <cmath>
#include <string>
#include <fstream>
using namespace std;
//const
const int Array_Row = 25;
const int Array_Col = 4;
//arrays
string letterGrade[Array_Row];
int myScores[Array_Row][Array_Col];
string names[Array_Row];
int main()
{
int count;
//int average;
ifstream inFile;
inFile.open("classData.txt");
int arraySize = 0;
if(inFile.is_open())
{
int counter = 0;
while(inFile.eof()==false)
{
inFile >> myScores[counter][0];
inFile >> myScores[counter][1];
inFile >> myScores[counter][2];
inFile >> myScores[counter][3];
getline(inFile, names[counter]);
counter++;
}
}else
cout << "Failed";
for(int counter = 0; counter < Array_Row-2; counter++)
{
for(int index = 0; index < Array_Col; index++)
{
cout << setw(4) << fixed;
cout << myScores[counter][index];
}
cout << names[counter] << endl;
}
inFile.close();
for(int counter = 0; counter < Array_Row-2; counter++)
{
cout << setprecision(2) << setw(2) << fixed;
double studentAverage = (myScores[counter][0] + myScores[counter][1] + myScores[counter][2] + myScores[counter][3])/4.0;
cout << "Student average is ";
cout << studentAverage;
cout << " ......" <<names[counter] << endl;
if(studentAverage >=90.00)
letterGrade[counter] = "A";
else if(studentAverage >=80.00 && studentAverage<=89.99)
letterGrade[counter] = "B";
else if(studentAverage >=70.00 && studentAverage<=79.99)
letterGrade[counter] = "C";
else if(studentAverage >=60.00 && studentAverage<=69.99)
letterGrade[counter] = "D";
else if(studentAverage <59)
letterGrade[counter] = "F";
cout << "Student letter grade is: "<< letterGrade[counter] << endl;
}
double classAverage = 0;
for(int counter = 0; counter < Array_Row-2; counter++)
{
classAverage += (myScores[counter][0] + myScores[counter][1] + myScores[counter][2] + myScores[counter][3]);
}
cout << "Class average is : "<< (classAverage/92.0);//calculate class average
int test1Total = 0;
for(int index = 0; index <Array_Row-2; index++)
test1Total += myScores[index][0];
int test1Average = (test1Total/23.0); //calculates test1 average
cout <<"\nStudent average for test 1: " << test1Average << setprecision(2) <<fixed;
int test2Total = 0;
for(int index = 0; index <Array_Row-2; index++)
test2Total += myScores[index][1];
int test2Average = (test2Total/23.0);
cout <<"\nStudent average for test 2: " << test2Average;//calculates test2 average
int test3Total = 0;
for(int index = 0; index <Array_Row-2; index++)
test3Total += myScores[index][2];
int test3Average = (test3Total/23.0);
cout <<"\nStudent average for test 3: " << test3Average;//calculates test3 average
int test4Total = 0;
for(int index = 0; index <Array_Row-2; index++)
test4Total += myScores[index][3];
int test4Average = (test4Total/23.0);
cout <<"\nStudent average for test 4: " << test4Average;//calculates test4 average
return 0;
}
I can't find the error you've posted, but the problem with the code is the getline(...) function.
This is getline's prototype:
istream& getline (istream& is, string& str);
as you can see it returns an istream which you cannot pass to the << operator.
What you can do is:
string str;
getline(inFile, name) >> str;
and then print:
cout << "The numbers are"
<< myArray[count][index]
<< str << endl;
You have an error in this statement
cout << "The numbers are"
<< myArray[count][index]
<< getline(inFile,name) << endl;
Operator >> performed from left to right. So first you output to cout
cout << "The numbers are"
Then you send to cout uninitialized value of myArray[count][index]
<< myArray[count][index]
And after that
<< getline(inFile,name) << endl;
Also, you have an error in using of getline. If your input file contain just space separated int values the right version is
inFile >> myArray[count][index];
cout << "The numbers are"
<< myArray[count][index] << endl;
My problem is that I cant get the getting the filename from the command line from the user, then using that filename to write the median, mode, and average. Im new to c++ so any tips or code fix would be great, and if you guys see anything else wrong please let me know, this is what I have, Im 99% done with it its just this filewriting thats giving me problems. Thank you
#include <iostream>
#include <fsteam>
#include <string>
using namespace std;
double Median(int [], int);
double Average(int [], int);
double Mode(int [], int);
int main(int argc, char *argv[])
{
ofstream outFile;
string filename = argv[1];
outputFile.open(filename.c_str());
if(!outFile)
{
cerr << "Error with the file.";
}
else
{
continue;
}
int *array;
int array_size;
cout << "How many students were surveyed? " << endl;
cin >> array_size;
if(array_size < 1)
{
cout << "Number of students surveyed must be greater than 1." << endl;
return(1);
}
else
{
array = new int [array_size];
}
cout << "Enter the number of movies each studen saw." << endl;
for(int i = 0; i < array_size; i++)
{
cout << "Student " << i+1 << ": " << endl;
cin >> array[i];
}
for(int i = 0; i < array_size; i++)
{
for(int j = i+1; j < array_size-1; j++)
{
if(array[i] > array[j])
{
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
double median = Median(array, array_size);
double average = Average(array, array_size);
double mode = Mode(array, array_size);
outFile << "Median: " << median << endl;
outFile << "Average: "<< average << endl;
outFile << "Mode: " << mode << endl;
return 0;
}
double Median(int arr[], int size)
{
double middle;
if(size%2 == 0)
middle = (arr[size/2] + arr[size/2-1])/2;
else
middle = arr[size/2];
return middle;
}
double Average(int arr[], int size)
{
double ave = 0;
for(int i = 0; i < size ; i++)
ave += arr[i];
ave = ave/size;
return ave;
}
double Mode(int arr[], int size)
{
int count, mode = 0;
for(int i = 0; i < size; i++)
{
count = 1;
while(arr[i] == arr[i+1])
{
count++;
i++;
}
if(count > mode)
mode = arr[i];
if(count > 1)
i--;
}
return mode;
}
You'll likely see something about this in the compiler, but I'll let you know anyways #include <fsteam> is <fstream>
I'm confused as to why you chose to put this
else
{
continue;
}
instead of nothing, since continue; just jumps to the end of the current iteration, which doesn't seem necessary here.
The rest of it seems fine. It's formatted to be easily read. If you have any errors post-testing, let me know.
EDIT: Sorry, I can't add comments yet, but in response to your comment, it's likely because of what I noted about <fstream> above. It's just a typo.
I tried it with following patch.
--- orig.cpp 2014-05-17 12:39:37.000000000 +0800
+++ new.cpp 2014-05-17 12:38:28.000000000 +0800
## -1,5 +1,5 ##
#include <iostream>
-#include <fsteam>
+#include <fstream>
#include <string>
using namespace std;
## -16,13 +16,13 ##
outputFile.open(filename.c_str());
- if(!outFile)
+ if(!outputFile)
{
cerr << "Error with the file.";
}
else
{
- continue;
+// continue;
}
## -64,9 +64,9 ##
double median = Median(array, array_size);
double average = Average(array, array_size);
double mode = Mode(array, array_size);
- outFile << "Median: " << median << endl;
- outFile << "Average: "<< average << endl;
- outFile << "Mode: " << mode << endl;
+ outputFile << "Median: " << median << endl;
+ outputFile << "Average: "<< average << endl;
+ outputFile << "Mode: " << mode << endl;
return 0;
}
I think that as following.
first, You type incorrectly with fsteam -> fstream.
second, you type incorrectly with outFile -> outputFile.
third, you must don't use continue without loop.
As result, I suggest you have more focus about typing error.
Better to check the count command line arguments.
int main(int argc, char *argv[])
{
if(argc <2 )
{
cout << "Specify out file name as command line argument";
return 0;
}
. . . . .
. . . . .
}
for more details,
http://www.cprogramming.com/tutorial/c/lesson14.html