c++ private array access and storing - c++

i need to store number and sum it , but the compiler say the a.num[i] is inaccessible... Here my code
class number{
private:
int num[12];
public:
number(){
}
int totalnumber(){
int total =0;
for( int i=0 ; i<12 ; i++){
total= total + num[i];
}
return total;
}
};
int main(){
number a;
int a;
cout<<"Enter number :";
cin>>a.num[i];
while(a.num[i] < 0){
cout<<"You've entered invalid input."<<endl;
cout<<"Enter number :"<<endl;
cin>>a.num[i];
}
cout<<"Total amount saved is : RM"<<number.totalnumber()<<endl;
return 0;
}
I think the number constructor need to do something, but i cant figure it out:( . Is there any way i can store the array inside a private array as declare in class number?

There are a couple of problems with your code:
First you defined 2 variables with the same name in the "main" function:
number a;
int a;
Then you try to access the variable "i" in "cin>>a.num[i];" but "i" has not be declared yet assigned in the "main" function.
I guess and think what you may try to achieve with your code is to sum a couple of numbers that are entered by the user.
In this case you may want to to use "for" loop to iterate over "i" and store the numbers read into the array in your object of the "number" class.
To store the numbers, you may want to implement a method for your class, like this, because you can't access a member variable like "int num[12]" from the ouside when it is declared as a private member:
void storeNum(int num, int i){
num[i] = num;
}
Third, you create an object of the class "number" with the name "a", but in the last line of your code, you tried to access the method "totalnumber" but you did not specify the object to invoke the method on, instead to wrote the class name.
And then you forget to
#include <iostream>
which is required by the C++ standard if you want to access library functions, which are defined the in the "iostream" header file. Additionally, you may want to write
using namespace std;
at the top of your file to tell the compiler that you want to import all the identifiers from the std namespace into your current namespace; That is, you wan't to write "cout" instead to "std::cout".
( Edit: To make this clear: You should never never never write "using namespace std" in production code... Never. Unless you're learning the language and trying things out.. Then it's okay. Just to keep this in mind for later... )
For example, the finished code could look like this:
#include <iostream>
using namespace std;
class number{
private:
int num[12];
public:
number(){};
int totalnumber(){
int total =0;
for( int i=0 ; i<12 ; i++){
total= total + num[i];
}
return total;
}
void storeNum(int number, int i) {
num[i] = number;
}
};
int main(){
number a;
for(int i = 0; i < 12; i++) {
cout << "Enter Number:";
int num = 0;
cin >> num;
a.storeNum(num,i);
}
cout<<"Total amount saved is : RM"<< a.totalnumber()<<endl;
return 0;
}
Hopefully, I could resolve your problem I helped you to understand the C++ language a little bit better.
Edit:
I noticed you tried to handle invalid user input in your code. That was a good idea (I assume you know at least another language ;) ). But it's more important to get you syntax correct. You can worry about error handling later...

Related

wrong output in vscode and codeblocks

This code snippet is supposed to return the reverse of the given integer and in the Sololearn compiler it works but in VSCode and Code::Blocks the output is different.
For 543 it returns -93835951 in VSCode and 694653940 in Code::Blocks.
Does anybody know why?
#include <iostream>
using namespace std;
int main()
{
int n, sum, a;
a = 0;
sum = 0;
cin >> n;
while (n>0)
{
a = n % 10;
sum = sum * 10 + a;
n = n / 10;
}
cout << sum;
return 0;
}
Here is the working version with a bit of refactoring but still keeping it very similar to your snippet:
#include <iostream>
int main( )
{
std::cout << "Enter a number: ";
int num { };
std::cin >> num;
int sum { };
while ( num > 0 )
{
const int remainder { num % 10 };
sum = sum * 10 + remainder;
num = num / 10;
}
std::cout << "The reversed number: " << sum << '\n';
}
A few general things to keep in mind:
Do not use using namespace std;. That's a bad practice. See Why is "using namespace std;" considered bad practice?.
Do not declare multiple variables in a single statement. That can lead to various issues.
Make sure to initialize your variables before using them if their initial values will be read and used in some operation. If the initial value is not used by anyone, then do not initialize the variable since it would be a waste of computing power.
Try to shrink the scope of variables as much as appropriate to reduce the risk of them being used accidentally by another statement that is not supposed to access those variables. In the above example, I declared remainder inside the scope of the while loop because it was not being used outside the loop.
And last but not least, avoid ambiguous identifiers like int a, int n, etc. These are not meaningful and purposeful names in this context. Use names that MAKE sense.
int n,sum,a=0;
the above expression only initializes the last variable 'a', leaving 'n' and 'sum' uninitialized.
although n is assigned a value in
cin >> n;
the variable 'sum' is likely to have a garbage value. That explains the different results.

Solved the given question below but not able to get the final output

A drawer contains socks of n different colors. The number of socks available of i'th color is given by a[i] where a is an array of n elements. Tony wants to take k pairs of socks out of the drawer. However, he cannot see the color of the sock that he is picking. You have to tell what is the minimum number of socks Tony has to pick in one attempt from the drawer such that he can be absolutely sure, without seeing their colors, that he will have at least k matching pairs.
My solution:
#include <bits/stdc++.h>
using namespace std;
class Solution{
public:
int find_min(int a[], int n, int k) {
int total , total_pairs , total_socks ;
for (int i = 0 ; i < n ;i++)
{
total_socks += a[i];
total_pairs += (a[i]/2) ;
}
total = total_socks - total_pairs + k ;
a = (int)total_socks ;
n = total_socks;
k = total;
}
};
// { Driver Code Starts.
int main() {
int t;
cin >> t;
while (t--) {
int n, k;
cin >> n;
int a[n];
for (int i = 0; i < n; i++) cin >> a[i];
cin >> k;
Solution obj;
cout << obj.find_min(a, n, k) << endl;
}
return 1;
}
But I get this error:
Error : error: invalid conversion from int to int* [-fpermissive]
a = (int)total_socks ;
The problem is because your trying to assign an int to a variable of type int* here: a = (int)total_socks ; I think what your looking for is a = (int*)total_socks ;. But still it is pointless as your not using the variable again (unless your actually planning on returning it). So is the rest of them, n and k.
Theres another problem with your code, the function int find_min(int a[], int n, int k) is of return type int. But in the function body, your not returning anything. This will result in undefined behavior. So make sure that you return something in that function.
Additional: Make sure you initialize all your variables. Over here: int total , total_pairs , total_socks ; you don't initialize it to any value so later on, it might not give you the result you require because it already contains junk.
And try not to use using namespace std; as its not a good practice. So is #include <bits/stdc++.h>. Include the files you want and use the :: operator to access their namespace instead.
Unrelated: Do you need a class just for that function? It seems like you don't (by looking at the code you have provided). Just keep the function in the global namespace but if you want it to be inside a namespace, put it inside one (ie: namespace Solution { ... }).

C++, function with changing amount of inputs (idk how to describe)

The funcion HIGHEST is all good and accepts variable number of arguments. The problem is how do I do variable amount of input? (idk what terms should be use to describe it, but examples should clear things up...)
/*cout << highest(n, A[0],A[1],A[2],A[3]) <<endl;
this is what I would like to achieve,
but with a change - the number of array changes with
the input file and n defines how many of these will be.
ex.: if n = 7 it needs to be (n, A[0],A[1],A[2],A[3], A[4], A[5], A[6])
*/
Duom.txt file if needed (i am now only working with 1st number 4 under it others will follow same/similar thing as 1st row they are not important now)
4
2008 5 2000.00 400.25
2010 5 4000.00 320.25
2009 9 3385.00 254.45
2008 6 1900.00 612.59
#include <iostream>
#include <iomanip>
#include <cmath>
#include <fstream>
#include <cstdarg>
using namespace std;
//Variable number of arguments in C++
int highest (int num,...) {
va_list valist;
int max = 0;
int a;
va_start(valist, num);
for (int i = 0; i < num; i++) {
a = va_arg(valist, int);
if(max < a) max = a;
else ;
}
va_end(valist);
return max;
}
int main () {
int n, A[25], B[25];
double C[25], D[25];
ifstream fd ("Duom.txt");
ofstream fr ("Rez.txt");
fd >> n;
cout << n <<endl;
for(int i = 0; i < n; i++){
fd >> A[i] >> B[i] >> C[i] >> D[i];
}
cout << highest(n, ) <<endl;
/*cout << highest(n, A[0],A[1],A[2],A[3]) <<endl;
this is what I would like to achieve,
but with a change - the number of array changes with
the input file and n defines how many of these will be.
ex.: if n = 7 it needs to be (n, A[0],A[1],A[2],A[3], A[4], A[5], A[6])
*/
return 0;
}
is there a specific reason you want the function Highest to get all array integers separately? Also - why did you choose to use an array instead of a vector?
Assuming that you want to use an array, I'd suggest to change the function's arguments as follows:
int highest (int num,int *arr);
where arr is the name of your array and in fact a pointer to the first integer of the array.
Then, inside the function, you can just access the array using subscript notation or dereferencing:
first_array_int=*(arr); //dereferencing example
second_array_int=*(arr+1); //dereferencing example
or
first_array_int=arr[0]; //subscript example
second_array_int=arr[1]; //subscript example
note that by doing that you can change the passed array within the function.
Again, I'd suggest to use a vector instead, then define the function:
int highest (int num,vector <int> *A);
if you want to pass a pointer, or:
int highest (int num,vector <int> A);
if you want to pass by value. Ofcourse, don't forget to include the vector library with
#include <vector>
I hope I understood your question well and that this is helpful.
Goodluck!
Guy

Convert userInput (string) to UserInput(int) mid for loop

I am working on a program that has to do with arrays. I decided that the input the user provides to be a string to later being converted to an integer once it is determined it is one. This way the program wouldn't run into an error when words/letters are entered. The issue I am having is the conversion from string to int. I want to change that because later in the program I am going to search the array for a given value and display it and its placement in the array. This is the code I have thus far:
#include <stdio.h>
#include <iostream>
using namespace std;
//check if number or string
bool check_number(string str) {
for (int i = 0; i < str.length(); i++)
if (isdigit(str[i]) == false)
return false;
return true;
}
int main()
{
const int size = 9 ;
int x, UserInput[size], findMe;
string userInput[size];
cout << "Enter "<< size <<" numbers: ";
for (int x =0; x < size; x++)
{
cin >> userInput[x];
if (check_number(userInput[x]))
{//the string is an int
}
else
{//the string is not an int
cout<<userInput[x]<< " is a string." << "Please enter a number: ";
cin >> userInput[x];}
}
int i;
for (int i =0; i < size; i++)
{
int UserInput[x] = std::stoi(userInput[x]); // error occurs here
}
for (int x= 0; x< size; x++)
{
if (UserInput = findMe)
{
cout <<"The number "<< UserInput[x] << "was found at " << x << "\n";
}
else
{
//want code to continue if the number the user is looking for isn't what is found
}
}
return 0;
}
Made comments here and there to kinda layout what I want the code to do and whatnot. I apperciate any help you can give, thank you.
This code:
int UserInput[x] = std::stoi(userInput[x]);
declares an int array of size x, to which you are assigning a single int (the result of std::stoi), which obviously doesn't work.
You need to assign an int to a particular index of the existing array, like this:
UserInput[x] = std::stoi(userInput[x]);
Given this comparison if (UserInput = findMe), which should actually be if (UserInput == findMe), it seems you want to declare a single int which stores the result of std::stoi. In that case, you should use a different name than the array, and write something like this:
int SingleUserInput = std::stoi(userInput[x]);
Also, please indent your code consistently, and compile with all your warnings turned on. Your code will be easier to read, and the compiler will point out additional problems with your code. And please don't use using namespace std;, it's a bad habit.
I don't understand why do u even need to use another loop to convert the string value to int. stdio.h header file does provides with preinstalled functions to make your work easier...
for (int x =0; x < size; x++)
{
getline(cin,userInput1[x]);
UserInput[x]=stoi(userInput1[x]);
}
stoi() function converts the string input to int, and you can call it dynamically as soon as you enter your string input,It will make you work easier and reduce the time complexity

Pointers for Member Functions

I am currently trying to create a program to calculate the mass of a rocket with given time values by passing an array to a member function of a class. I want to use a pointer for the array. How do I go about doing that. Should the pointer be initialized in int main or the class. Any suggestions appreciated.
#include <cmath>
#include <cstring>
#include <fstream>
#include<iostream>
using namespace std;
class equip
{
public:
double mass[999999999], velocity, height, *time[999999999];
double calcmass(double* time);
double calcvelocity();
double calcheight();
double calctime();
private:
double T = 7000;
double g = 32.2;
double K = 0.008;
};
double equip::calcmass(double* time)
{
int i = 0;
for(i=0; i=999999999; i++)
{
return mass[i] = (3000 - 40 * time[i]) / g;
}
}
int main()
{
int i = 0;
equip rocket;
ifstream infile;
string filename;
cout<<"Enter input file name for time values: ";
cin>>filename;
infile.open(filename.c_str());
while(infile.fail())
{
cerr<<"Error opening file. \n";
cout<<"Enter file name: ";
cin>>filename;
infile.open(filename.c_str());
}
for(i=0; i<999999999; i++)
{
infile>>rocket.time[i];
}
for(i=0; i<999999999; i++)
{
cout<<rocket.mass[i];
}
return 0;
}
equip is a very large object. About 14 gigabytes in fact.
Automatic variables such as equip rocket are allocated on the execution stack. The default size of the execution stack on most desktop systems is about 1 to few megabytes.
A 14 gigabyte object will most definitely overflow a 1 megabyte stack.
Solution: Always use dynamic allocation for large arrays such as used here. Simplest solution is to use std::vector. Also, are you certain that you need the arrays to be that big?
for(i=0; i=999999999; i++)
This loop looks like it will never end because 999999999 is always true.
{
return ....
But in fact, the loop never repeats because the function immediately returns. Neither choice makes sense, although in combination their silliness sort of cancel each other out.
Change the size of array to a practical real number. If can't , go through Dynamic memory allocation.