garbage value is obtained - c++

this is a sample of my code. i am getting the value for maximum height. but my minimum height is a garbage value. what am i doing wrong
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
#include <sstream>
using namespace std;
#define MAX 20
struct DATA
{
int id;
string name;
float height;
}numarray[MAX];
int main()
{
int num = 0;
numarray[num].height = fstr3;// contains float values from a file
float minimum, maximum;
minimum = numarray[0].height;
maximum = numarray[0].height;
for(int i = 0; i < MAX; i++)
{
{
if(numarray[i].height < minimum)
{
minimum = numarray[i].height;
}
else if(numarray[i].height > maximum)
{
maximum = numarray[i].height;
}
}
cout<< minimum<< " " << maximum<< endl;
return 0;
}
}

Garbage in, garbage out. It looks like your input routine (which you didn't post) may be populating the data incorrectly. I'd look at the input data in the debugger (even if your choice of debugger is printf()).

Your code assumes that minimum is unequal to the maximum.
Solution second if should be on its own and not in else clause from first.

assuming you do initialize the array in your real code, with these modifications:
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
#include <sstream>
using namespace std;
#define MAX 20
struct DATA
{
int id;
string name;
float height;
}numarray[MAX];
int main()
{
int num = 0;
numarray[num].height = fstr3;// contains float values from a file
float minimum, maximum;
minimum = numarray[0].height;
maximum = numarray[0].height;
for(int i = 1 /* skip 0 - already read */; i < MAX; i++)
{
if(numarray[i].height < minimum)
{
minimum = numarray[i].height;
}
// remove the else here
if(numarray[i].height > maximum)
{
maximum = numarray[i].height;
}
}
// move outside the loop
cout<< minimum<< " " << maximum<< endl;
return 0;
}
this should be OK

Related

std::cin string to int array with variable length input

I have a task where i need to revert a list of variable length numbers. This could be "1 2 3" or "5 6 7 8 9 10".
The sorting itself works fine.
But I can't figure out how to read the user input (with variable length) and then only execute the reverseSort once.
How can I read the user input into an array where each index is based on the space between the numbers?
Here is my code:
#include <iostream>
#include <string>
using namespace std;
bool sorted = true;
int temp;
int * arr;
int arrLength = 5;
int arrs;
// int arr = {1,2,3,4,5};
void reverseSort(int arr[], int n){
sorted = true;
for (int i = 0; i < n-1; i++){
if (arr[(i + 1)] > arr[i]){
temp = arr[i];
arr[i] = arr[i+1];
arr[i+1] = temp;
sorted = false;
}
}
if (!sorted){
reverseSort(arr,n);
}
}
int main(void){
// get user input !?!?!?!?!
cin >> arrs;
cout << arrs;
reverseSort(arr,arrLength);
for (int i = 0; i < arrLength; i++){
std::cout << arr[i] << " ";
}
return 0;
}
If you don't know number of inputs you need struct that can be resized. std::vector is good for it. For adding new data you can use member function push_back.
You can read the input line as std::string (by std::getline) and you can open new stream with read data (std::istringstream). Further one can read values from new stream.
And I think you can use std::sort instead of reverseSort (but for 'reverse' you need use std::greater as comparator).
#include <vector>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <algorithm>
int main(void){
std::vector<int> arrs;
// read only one line
std::string input;
std::getline(std::cin, input);
std::istringstream row(input);
int x;
while (row >> x)
{
arrs.push_back(x);
}
//like your reverseSort
std::sort(arrs.begin(), arrs.end(), std::greater<int>{});
for (auto var : arrs) {
std::cout << var << "; ";
}
return 0;
}

Stack around the variable 'sortArray' was corrupted

Run-Time Check Failure #2 - Stack around the variable 'sortArray' was corrupted.
I am getting this on final line, the program is meant to create a list of random numbers and then sort them(WIP). I thought it might be the array size being smaller than the number of lines in test.txt so I increased it from 100 to 101 to no avail.
//#include <cstdlib>
#include <iostream>
#include <fstream>
#include <ctime>
#include <string>
using namespace std;
int main()
{
//srand(time(NULL));
std::ofstream outfile("C:\\Users\\smasher248\\Desktop\\test.txt");
int randomNumber;
for (int x = 0; x < 100; x++)
{
randomNumber = rand() % 9000 + 1000;
outfile << randomNumber <<"\n";
}
outfile.close();
std::ifstream infile("C:\\Users\\smasher248\\Desktop\\test.txt");
std::string lineHolder;
int lineCounter = 0;
int sortArray[101];
while (std::getline(infile, lineHolder))
{
sortArray[lineCounter] = stoi(lineHolder);
cout << sortArray[lineCounter] << "\n";
lineCounter++;
}
infile.close();
int swapContainer;
for (int i = 0; i < 101; i++)
{
if (sortArray[i] > sortArray[i+1])
{
swapContainer = sortArray[i];
sortArray[i] = sortArray[i + 1];
sortArray[i + 1] = swapContainer;
}
std::ofstream sortedFile("C:\\Users\\smasher248\\Desktop\\test_sorted.txt");
sortedFile << sortArray[i] << "\n";
}
}
You just need to make a few changes into your code.
Include <algorithm> in the beginning of your code
In the ofstream(...), add ..., std::ios::app) to append into the file.
To sort the array, remove the entire block of conditional expression above the ofstream syntax and add std::sort(sortArray, sortArray + 100) outside of the loop.
Change the value 101 to 100 in that For loop.
And you're done.

Why am i getting out-of-range error?

I can't seem to find where my issue is. Its a three file program with aDie class in one file, aHistogram class in another file, and the main.cpp file. It is supposed to print a histogram constructed with X's to show how many times the die landed on each of the six faces. I cant move forward because of the vector error... There may be other issues with the program that i haven't worked out yet, but I just want to know about the vector error. Thank you.
main.cpp:
#include <iostream>
#include <stdlib.h> //srand and rand
#include <time.h> //Time
#include <vector>
#include <algorithm>
#include "aHistogram.h"
#include "aDie.h"
using namespace std;
int main()
{
srand (time(NULL));
int numRolls;
const int maxLengthOfLine = 50;
cout << "How many rolls? " << endl;
cin >> numRolls;
aDie fairDie;
aHistogram fairHistogram;
//For Loop rolls the die and updates the histogram vector ~~binHistogram.
for(int i = 0; i < numRolls; i++)
{
int face = fairDie.roll();
fairHistogram.update(face);
}
cout << "*******************" << endl;
cout << "*****Histogram*****" << endl;
cout << "*******************" << endl;
fairHistogram.display(maxLengthOfLine);
}
aDie.h:
#ifndef ADIE_H_INCLUDED
#define ADIE_H_INCLUDED
#include <stdlib.h>
#include <time.h>
#include <vector>
#include <algorithm>
using namespace std;
/********************************************/
/*******Definition of aDie class*************/
/********************************************/
class aDie
{
public:
int roll(); //return an integer between 1 and 6 to represent what face appears when the die is rolled.
aDie(); //Default constructor
~aDie(); //Destructor
private:
int numFaces = 6;
};
int aDie::roll()
{
return ((rand() % numFaces) + 1); //returns a random number between 1 and 6
}
aDie::aDie()
{
cout << "Dice Roll...." << endl;
return;
}
aDie::~aDie()
{
return;
}
#endif // ADIE_H_INCLUDED
aHistogram.h:
#ifndef AHISTOGRAM_H_INCLUDED
#define AHISTOGRAM_H_INCLUDED
#include <algorithm>
#include <stdlib.h>
#include <vector>
using namespace std;
/********************************************/
/*******Definition of aHistogram class*******/
/********************************************/
class aHistogram
{
public:
void update(int face);
void display(int maxLengthOfLine);
int Count(int face);
void clear();
aHistogram(); //Constructor
~aHistogram(); //Destructor
private:
vector<int> binHistogram;
const int numFaces = 6;
int totalRolls;
int largeBin = 0;
double xScale;
};
//Adds a count to each face every time the die lands on said face.
void aHistogram::update(int face)
{
binHistogram.at(face) += 1;
return;
}
//Displays the histogram with X's
//maxLengthOfLine represents the maximum number of x’s to be printed for the largest bin count.
void aHistogram::display(int maxLengthOfLine)
{
xScale = maxLengthOfLine / largeBin;
for(int i = 1; i <= 6; i++)
{
cout << i << " : " << Count(i) << " : ";
int numXs = xScale * binHistogram.at(i);
for(int j = 0; j < numXs; j++)
{
cout << "X";
}
}
}
//To be called AFTER aHistogram::update
//Returns a count of how many times for each face of the die
int aHistogram::Count(int face)
{
//For Loop determines the largest bin count
for (int i = 1; i < numFaces; i++)
{
while (binHistogram[i] >= largeBin)
{
largeBin = binHistogram.at(i);
}
}
//
return binHistogram.at(face);
}
void aHistogram::clear()
{
binHistogram.clear();
return;
}
//Defines the DEFAULT CONSTRUCTOR. Sets all elements of the histogram to zero.
aHistogram::aHistogram()
{
return;
}
//Defines the DESTRUCTOR. Clears vector after use.
aHistogram::~aHistogram()
{
binHistogram.clear(); //Clears vector
return;
}
#endif // AHISTOGRAM_H_INCLUDED
I didnt find the place where you initialize the histogram this might be the problem. But even if you fix that, you will hit two other bugs:
for (int i = 1; i < numFaces; i++)
{
while (binHistogram[i] >= largeBin)
{
largeBin = binHistogram.at(i);
}
}
you are accessing elements 1....6 when probably it should be 0...5. Same problem in the line where you have
largeBin = binHistogram.at(i);
which is most likely the line that causes the error (the one above wont be so nice to tell you what is the problem but just crash your program).
You never change the size of the vector in the aHistogram class, which means its size will always zero. Any index will be out of bounds.
For things like histograms I would actually recommend you to use std::unorderd_map instead of std::vector, with the "face" being the key and the count being the data. Then you could do e.g.
binHistogramMap[face] += 1;
without worrying about the element for face not existing (it will be created and initialized to zero if the entry doesn't exist).

sorting array of strings one off

This code is supposed to make a array of strings, randomly order them, and then print the order. Unfortunately it adds a blank line in one of the spaces ( i think this is getline's doing). Any ideas how to fix that? I tried setting array [0] = NULL; it complains about operators...
#include <iostream>
#include <stdio.h>
#include <conio.h>
#include <time.h>
#include <string>
#include <cstdlib>
using std::cout;
using std::endl;
using namespace std;
void swap (string &one, string &two)
{
string tmp = one;
one = two;
two = tmp;
}
int rand_loc (int size)
{
return (rand() % size);
}
int main()
{
srand(time(NULL));
int size;
cin >> size;
string *array = new string[size];
//array[0] = NULL ;
for (int x = 0; x < size; x++)
{
getline(cin, array[x]);
}
//for (int x = 0; x < size; x++)
//{
// swap (array[rand_loc(size)], array[rand_loc(size)]);
//}
cout << endl;
for (int x = 0; x < size; x++)
{
//out << array[x] << endl;
int y = x + 1;
cout<<y<<"."<<" "<<array[x]<<endl;
}
delete[] array;
}
The first call to getline() will immediately hit the newline that the user entered after inputting size, and will therefore return an empty string. Try to call cin.ignore(255, '\n'); before the first call to getline(). This will skip up to 255 (an arbitrarily selected number) characters until a \n is encountered (and the newline will be skipped as well).
Edit: As #Johnsyweb and #ildjarn point out, std::numeric_limits<streamsize>::max() is a much better choice than 255.

C++ Integration Solution using Riemann Sum : Loses validity for greater than 10 partitions

In an effort to code the briefest solution I could for an approximation of the integral using Riemann sums, I ran into a strange problem: if the user requested a partition count in excess of 10, the program failed. Any thoughts? Here's the code:
// The Integral
#include <algorithm>
#include <iomanip>
#include <ios>
#include <iostream>
#include <stdexcept>
#include <iomanip>
using std::cin; using std::cout;
using std::endl;
int func (int x);
int main ()
{
cout << "Please enter left and right bounds: ";
int left, right;
cin >> left >> right;
cout << "Please enter a # of partitions (>0): ";
int R;
cin >> R;
int width = (right - left) / R;
int total = 0;
for (int i = 0; i < R; ++i) {
total += func(left + width*i);
}
cout << "The integral is: " << total << endl;
return 0;
}
int func (int x)
{
return x*x;
}
Using a partition size of greater than 10 is not your actual problem.
Your are using integers for your variables and function return value, when you should be using float or double.
For instance:
int width = (right - left) / R;
If (right - left) < R width will be zero!
on a side note, unless you plan on expanding this small prog, you're including way to many useless stuff. this is all you'd need for this prog:
#include <iostream>
#include <cstdio>
using namespace std;
int func (int x)
{
return x*x;
}
int main()
{
// if you have your main() at the bottom, you dont have to declare other functions on top.
}
cheers :)
Another comment:
In my opinion the for-loop in your code does not compute the correct Riemann-sum.
I think it should look like this:
for (int i = 0; i < R; i++) {
total += func(left) * width;
left += width;
}
Cheers :)