Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 months ago.
Improve this question
This has somehow become susceptible to buffer overflow. Not sure why or how to fix it?
ps. I am new to programming and any tips to improve the overall quality of the code would be greatly appreciated.
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int numberSeries[] = { 1 };
int seriesSize;
int checkOrder = 1;
int counter = 0;
int i = 0;
string arr[] = { "test" };
string value;
string import;
string fileLocation;
void CreateArrayFromFile(string fileLocation);
void InputNumbers();
void PrintArray();
int Iteration(int size, int array[]);
void SwapNumbers(int arrayLocation, int array[]);
int main()
{
cout << "What you like to numbers 'import' from file or 'manually' enter the numbers? \n";
cin >> import;
if (import == "import") {
cout << "Input file location using full path: ";
cin >> fileLocation;
CreateArrayFromFile(fileLocation);
}
else if (import == "manually") {
InputNumbers();
PrintArray();
while (counter < seriesSize) {
Iteration(seriesSize, numberSeries);
}
}
else {
cout << "INVALID SELECTION";
}
}
void InputNumbers() {
cout << "What is the required size of the array? \n";
cin >> seriesSize;
cout << "Enter " << seriesSize << " numbers: \n";
for (int i = 0; i < seriesSize; i++) {
cin >> numberSeries[i];
}
cout << "\n";
}
void PrintArray() {
cout << "Here are your current numbers: \n";
for (int i = 0; i < seriesSize; i++) {
cout << numberSeries[i] << " ";
}
cout << "\n";
}
int Iteration(int size, int array[]) {
for (int i = 0; i < (seriesSize - 1); i++) {
if (numberSeries[i] > numberSeries[i + 1]) {
SwapNumbers(i, numberSeries);
counter = 0;
}
else if (numberSeries[i] <= numberSeries[i + 1]) {
counter++;
}
}
if (counter >= seriesSize) {
cout << "YOUR NUMBERS HAVE BEEN SORTED\n\n";
}
else {
PrintArray();
cout << "Iteration complete!\n\n";
}
return 0;
}
void SwapNumbers(int arrayLocation, int array[]) {
int tempSwapOne, tempSwapTwo;
//store each number
tempSwapOne = array[arrayLocation];
tempSwapTwo = array[arrayLocation + 1];
//assign number to new location
array[arrayLocation] = tempSwapTwo;
array[arrayLocation + 1] = tempSwapOne;
}
void CreateArrayFromFile(string fileLocation) {
ifstream file;
file.open(fileLocation, ios::in);
int* ptr = (int*)malloc(sizeof(file));
cout << *ptr;
string line;
int i = 0;
if (file.is_open()) {
while (!file.eof())
{
getline(file, line);
arr[i] = line;
i++;
}
seriesSize = i;
}
else {
cout << "File could not be opened. Check path is correct...\n\n";
return;
}
for (i = 0; i < seriesSize; i++) {
int tempNumber = stoi(arr[i]);
numberSeries[i] = tempNumber;
cout << numberSeries[i] << " ";
}
cout << "\nTotal numbers: " << seriesSize;
}
I tried to assign the correct amount of memory but I have no idea how to figure out the correct amount.
Use std::vector instead. It handles the memory management and will automatically resize.
I wrote a code to manage a coffee machine,
I have a function findC that finds the cheapest capsule in the capsule array
a different function of mine findVP that is supposed to use the findC function's output as variables. however, when I pass the variables mp, ind = findC(prices_copy, quantities_copy, SIZE);
and print them it passes them as 0;
but the 2nd cout : cout << findC(prices_copy, quantities_copy, SIZE); prints the correct output.
why is this ? and how can I pass the output of the function to another
/******************************************************************************
Online C++ Compiler.
Code, Compile, Run and Debug C++ program online.
Write your code in this editor and press "Run" button to compile and execute it.
*******************************************************************************/
// Example program
#include <iostream>
#include <string>
#include <bits/stdc++.h>
using namespace std;
#define SLEEVE 10
#define SIZE 10
#define N 5
#define BUDGET 70
//int CapsuleKind[10] = {"JOE","MAC","NES","jamaica","brazil","columbia","MOJO","CLUB","JHON","COF"};
float findMostExpensiveCapsule( float prices[], int size ) // 1
{
float max = prices[0];
int count = 0;
for(int i = 1; i < size; i++)
{
if (prices[i] > max)
{
max = prices[i];
}
}
cout << "The maximum price " << max << " is found on indexes: " ;
for (int i = 0; i < size; i++)
{
if (prices[i] == max)
{
cout << i << " ";
count++;
}
}
cout << endl;
cout << "The maximum number appears " << count << " times." << endl;
return max;
}
int findStrongestCapsuleInStock( int quantities[], int size, int sleeve ) // 2
{
return 0;
}
void SellCapsules( int quantities[], int Qty, int index) // 10
{
quantities[index] = quantities[index] - Qty;
cout << "SOLD " << Qty << " capsules to the Customer, the total now is: " << quantities[index] << endl;
}
float findC( float prices[],int quantities[], int size ) // 9
{
float min = 99999;
int count = 0;
float index=0;
//sort(prices, arr + n);
for(int i = 0; i < size; i++)
{
if (quantities[i] >= SLEEVE)
{
if(prices[i] < min){
min = prices[i];
index= i;
}
else continue;
}
}
cout <<"the minimum price is : " << min << " ---- the index is : " << index << endl;
return min, index;
}
void findCheapestSleeve( float prices[],int quantities[], int size )
{
float min = prices[0];
int count = 0;
int index=0;
for(int i = 0; i < size; i++)
{
if (prices[i] < min)
{
if(quantities[i] > SLEEVE){
min = prices[i];
index= i;
}
else continue;
}
}
cout <<"the minimum price is : " << min << " ---- the index is : " << index << endl;
}
void showAllCapsulesInStock( int quantities[], float prices[], int size, int sleeve) // 3
{
for (int i = 0; i < size; i++)
{
cout << "capsule kind: " << i << " ---- sleeves available : " << (quantities[i]/sleeve) << " ---- price(for 1 sleeve): " << (prices[i]*sleeve)<< endl;
}
}
float findVP( float prices[], int quantities[], int size, float nis, int sleeve ) //4
{
float mp=0;
float ind =0;
float prices_copy[size];
int quantities_copy[size];
for(int i=0; i<size; i++){
prices_copy[i] = prices[i];
quantities_copy[i] = quantities[i];
}
mp, ind = findC(prices_copy, quantities_copy, SIZE);
cout << "The lowest price sleeve is: " << mp * 10 << " --- the capsule kind is: " << ind <<endl;
cout << findC(prices_copy, quantities_copy, SIZE);
}
void findValueForMoneyPackage( float prices[], int quantities[], int size, float nis, int sleeve )
{
int sleeve_num[size];
float sleeve_price[size];
float min=0;
int index = 0;
int counter=0;
float quant = 0;
for (int i=0; i < size; i++)
{
sleeve_num[i] = (quantities[i]/sleeve);
sleeve_price[i] = (prices[i] * sleeve);
}
//min, quant = findCheapestSleeve(sleeve_price, quantities, 10);
cout << "the cheapest sleeve costs : " << min << " and its of kind :" << quant << endl;
}
void addMoreCapsules( int quantities[], int size ) // 5
{
char answer;
int plus;
for (int i = 0; i < size; i++)
{
cout << "do you want to add capsules to capsule kind " << i << "? (Y/N) " << endl;
cin >> answer;
if (answer == 'Y')
{
cout << "How many capsules do you want to add (inter a number) " << endl;
cin >> plus;
if (plus > 0)
{
quantities[i] = quantities[i] + plus;
cout << "Added " << plus << " capsules to the inventory, the total now is: " << quantities[i] << endl;
}
}
else
{
continue;
}
}
}
// Driver Code
int main()
{
bool flag = false;
int option;
float prices[] = { 1.2, 2.2, 2.5, 1.7, 2.2, 3, 2.8, 2.5, 2.9, 3.7 };
int quantities[] = { 14, 22, 25, 13, 22, 33, 50, 60, 33, 25 };
while (flag != true)
{
cout << "Please choose an option , has to be a number 1-6" << endl;
cin >> option;
if (option == 1)
{
findMostExpensiveCapsule(prices,SIZE);
}
else if ( option == 3)
{
showAllCapsulesInStock(quantities, prices, SIZE, 10);
}
else if (option == 4){
findVP(prices, quantities, SIZE, BUDGET, SLEEVE);
}
else if(option == 5){
addMoreCapsules(quantities,SIZE);
}
else if(option == 9){
findC(prices, quantities, SIZE);
}
else
{
flag = true;
}
}
cout << "GoodBye!" << endl;
return 0;
}
This
return min, index;
doesn't do what you think it does. You obviously think it's going to return two values. But actually it just returns index.
This
mp, ind = findC(prices_copy, quantities_copy, SIZE);
doesn't do what you think it does. You obviously think it's going to assign the two returned values from findC to the variables mp and ind. But actually it's going to return the single value returned by findC to the variable ind and ignore mp.
If you want to know precisely what these constructs do then look up the comma operator, but I guess the moral of the story is that just because you can get some plausible looking code to compile it doesn't mean that it's going to do what you expected it to do.
So the real question is how to return two values from a function in C++. There are actually several possible approaches. Here's a question that reviews some of them, Returning multiple values from a C++ function.
I have a class ComplexesSet which represent a set of complexes numbers. I have to use this class to write a program which reads the complex numbers from keyboard and create a menu like that: press 1 to add a number in the set, press 2 to delete a number from set and press 0 to exit the program.
This is my program:
HEADER FILE
#pragma once
#include <iostream>
using namespace std;
#define DIMMAX 10;
class Complex {
int re, im;
public:
Complex() {
re = im = 0;
}
Complex(int re, int im) {
this->re = re;
this->im = im;
}
void display() {
cout << " (" << re << ", " << im << " ) ";
}
int equal(Complex c2); // check the equality between 2 complex numbers.
void read(); // reads a complex number
};
class ComplexesSet {
Complex* v; // the complex numbera array
int dim; // the maximum dimension of the array
int n; // the current number of complex numbers in the set
public:
ComplexesSet();
ComplexesSet(int d);
~ComplexesSet();
void addNumber(Complex); // add a number in set
void deleteNumber(Complex); // delete a number from set
void displaySet(); // display the set
};
METHODS FILE
#include "multime.h"
#include <iostream>
using namespace std;
int Complex::equal(Complex c2) {
if (this->re == c2.re && this->im == c2.im) {
return 1;
}
else {
return 0;
}
}
void Complex::read() {
cout << "Enter the real part: ";
cin >> this->re;
cout << "Enter the imaginary part: ";
cin >> this->im;
cout << endl;
}
ComplexesSet::ComplexesSet() {
cout << "Set of complexes numbers: ";
dim = DIMMAX;
v = new Complex[dim];
n = 0;
}
ComplexesSet::ComplexesSet(int d) {
cout << "ComplexesSet(" << d << ")";
dim = d;
v = new Complex[dim];
n = 0;
}
ComplexesSet::~ComplexesSet() {
cout << "~ComplexesSet" << endl;
if (v) {
delete[] v;
}
v = nullptr;
dim = -1;
n = -1;
}
void ComplexesSet::addNumber(Complex num) {
int ok = 0;
if (n < dim) {
for (int i = 0; i < n; i++) {
if (v[i].equal(num)) {
ok = 1;
i = n + 1;
}
}
if (ok) {
cout << "This element is already in the set.";
}
else {
v[n] = num;
n++;
}
}
else {
cout << "The set is full.";
}
}
void ComplexesSet::deleteNumber(Complex num) {
int i;
if (n != 0) {
for (i = 0; i < n; i++) {
if (v[i].equal(num)) {
break;
}
else {
cout << "This element does not exists.";
}
}
if (i < n) {
n = n - 1;
for (int j = i; j < n; j++) {
v[j] = v[j + 1];
}
}
}
else {
cout << "The set is empty.";
}
}
void ComplexesSet::displaySet() {
cout << "\n The set: {";
if (n) {
for (int i = 0; i < n; i++) {
v[i].display();
}
}
cout << "}.\n\n";
}
MAIN FILE:
#include "multime.h"
#include <iostream>
using namespace std;
int main() {
ComplexesSet m;
Complex num;
int option;
int x;
do {
cout << endl << "1 - ADD A NUMBER\n 2 - DELETE A NUMBER\n 0 - EXIT THE PROGRAM";
cin >> option;
switch (option) {
case 1:
cout << endl << "Enter the number you want to add: ";
num.read();
//? How to call addNumber method from ComplexesSet class?
// m.displaySet ?;
break;
case 2:
cout << endl << "Enter the number you want to delete: ";
num.read();
//? How to call deleteNumber method from ComplexesSet class?
// m.displaySet ?;
break;
}
} while (option >= 1 && option <= 2);
system("pause");
return 0;
}
I got stuck in the main file. How to call the addNumber and deleteNumber methods in order to add and delete a complex number from the set? Also, after pressing "1" or "2", after I read the number, I need to display the set.
This question already has answers here:
How to make cin take only numbers
(2 answers)
Closed 6 years ago.
So the requirements for this program is to be able to increment arrays of the same size (size from 5 to 15 indexes) and increment each element in the array by one using for and while loops. The last task is to take values from the first array and put them in reverse order and assign them to the second array.
So everything works as normal, and the program rejects invalid inputs and does not go into an infinite loop. However, the program accepts some inputs that are not wanted.
For example, I would input something like '12 a' or '7 asdfkla;j lasnfg jasklgn asfg' and it would go through. It is interesting too because the code registers only 12 or 7 and completely ignores the rest. I think it is because once it hits a non-integer character, it would stop ignore the rest.
Why is it ignoring the rest of the input? And is there a way to catch this error from going through?
Also, if you see anything that catches your eye, feel free to critique c: I am always looking to improving.
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main() {
srand(time(NULL));
int x;
int j = 0;
bool not_valid = true;
system("color f");
cout << "Program will ask for an input for the size of an array.\n"
<< "With the array size defined, program will generate semi-\n"
<< "true random integers from 0 to 8. First array will then\n"
<< "be assigned to the second in reverse (descending) order.\n\n";
do {
cout << "Enter array size (0 - 15): ";
cin >> x;
if (x >= 5 && x <= 15) {
not_valid = false;
cout << "\nArray size: " << x << endl;
}
else {
cout << "Invalid input.\n\n";
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
} while (not_valid);
int *arr0;
int *arr1;
arr0 = new int[x];
arr1 = new int[x];
for (int i = 0; i < x; i++) {
arr0[i] = rand() % 9;
}
for (int i = 0; i < x; i++) {
arr1[i] = rand() % 9;
}
cout << "\nARRAY 0 (unmodified, for):\n";
for (int i = 0; i < x; i++) {
cout << arr0[i] << "\t";
}
cout << "\n\nARRAY 0 (modified, for):\n";
for (int i = 0; i < x; i++) {
arr0[i]++;
cout << arr0[i] << "\t";
}
cout << "\n\nARRAY 1 (unmodified, while):\n";
for (int i = 0; i < x; i++) {
cout << arr1[i] << "\t";
}
cout << "\n\nARRAY 1 (modified, while):\n";
while (j < x) {
arr1[j]++;
cout << arr1[j] << "\t";
j++;
}
int second = x - 1;
for (int i = 0; i < x; i++) {
arr1[second] = arr0[i];
second--;
}
j = 0;
cout << "\n\nARRAY 1 (array 0, descending):\n";
while (j < x) {
cout << arr1[j] << "\t";
j++;
}
cout << endl << endl;
system("pause");
return 0;
}
Take input in string and then check if it's a number or not.
Example:
#include<iostream>
#include<sstream>
#include <string>
using namespace std;
int main()
{
string line;
int n;
bool flag=true;
do
{
cout << "Input: ";
getline(cin, line);
stringstream ss(line);
if (ss >> n)
{
if (ss.eof())
{
flag = false;
}
else
{
cout << "Invalid Input." << endl;
}
}
}while (flag);
cout << "Yo did it !";
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
// Number Sorting Algorithm - Trey Taylor 2014
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
int main() {
int numbersort [] = {200, 85, 63, 4}
cout << "The numbers scrambled are: ";
cout << numbersort[0] << ", ";
cout << numbersort[1] << ", ";
cout << numbersort[2] << ", ";
cout << numbersort[3] << ", " << endl;
firstlast:
if (numbersort[0] > numbersort[1]) {
int temp = 0;
temp = numbersort[0];
numbersort[0] = numbersort[1];
numbersort[1] = temp;
}
if (numbersort[1] > numbersort[2]) {
int temp = 0;
temp = numbersort[1];
numbersort[1] = numbersort[2];
numbersort[2] = temp;
}
if (numbersort[2] > numbersort[3]) {
int temp = 0;
temp = numbersort[2];
numbersort[2] = numbersort [3];
numbersort[3] = temp;
}
while (numbersort[0] > numbersort[1]) {
goto firstlast;
}
cout << "The numbers unscrambled are: ";
cout << numbersort[0] << ", ";
cout << numbersort[1] << ", ";
cout << numbersort[2] << ", ";
cout << numbersort[3] << ", ";
}
Does anybody know if there is a way to use a for or while loop to rearrange the numbers in the array into ascending order from left to right rather than just using 3 if statements
You could use std::sort or bubble sort algorithm(link how it works). Algorithm checks is current number in loop bigger from next one. If it is change those numbers in array. At the end you get the biggest number on the end of array and smallest at beggining of array.
int main()
{
int numbersort[] = { 200, 85, 63, 4 };
int temp = 0;
// This loop sorts all numbers in the array
for (int z = 0; z < 4; ++z)
{
// This loop sorts only one number to the end
for (int i = 0; i < 3; ++i)
{
if (numbersort[i] > numbersort[i + 1])
{
temp = numbersort[i];
numbersort[i] = numbersort[i + 1];
numbersort[i + 1] = temp;
}
}
}
cout << "Sorted numbers" << endl;
for (int i = 0; i < 4; ++i)
{
cout << numbersort[i] << endl;
}
system("pause");
return 0;
}
Something like this:
i = 0;
while (i < (sizeof(numbersort)/sizeof(numbersort[0])) - 1)
{
if (numbersort[i] >= numbersort[i + 1])
{
std::swap(numbersort[i], numbersort[i + 1]);
i = 0;
}
else
{
++i;
}
}