Error converting int y to vector <int> any ideas? - c++

I'm new to C++ and am not sure what's wrong. This is a task I have been given in my programmging course at uni which is meant to take user input of a vector of grades and determine whether the grade is a passing one. When I compile I end up getting an error stating q1.cpp:30:21: error: could not convert ‘y’ from ‘int’ to ‘std::vector’
Not overly sure why. Sorry about the bad formatting.
I've added the code but not sure how to wrap it.
#include <vector>
#include <cstdlib>
#include <iostream>
using namespace std;
int calcNumberOfPasses(vector<int> grades){
int x;
for (int i=0; i<grades.size(); i++){
cin >>grades[i];
}
cin >> x;
}
int main() {
int y;
vector<int> nGrade;
nGrade.push_back(y);
cout << "Enter how many grades you want to enter";
for (int i=0; i<nGrade.size();i++){
cin >> nGrade[i];
}
cin >> y;
if (y>=50){
cout << "this is a passing grade";
}
calcNumberOfPasses(y);
}

The function calcNumberOfPasses is expecting a parameter of type vector<int>, you are passing it a parameter of type int. That much you can work out from the error message.
You are copying an undefined value into the vector on this line:
nGrade.push_back(y); // y hasn't been initialised yet, you probably want to remove this line.
Following that you are looping over the size of the grades vector, which hasn't been initialised yet.
Chances are, you want to do calcNumberOfPasses(nGrades);.
As an aside, you should use a reference to the vector, to avoid copying it.
In summary, I would through all of this code away and start again. No offence!

A vector is a collection -- a grouping of items of some base class. It's conceptually similar to an array. What you are doing is trying to repeatedly load a single variable and then pass that into a function that expects a vector.
Try breaking down the steps of the function you're writing. You are:
Adding a single, uninitialized int to a vector.
Trying to retrieve a number to control the number of grades you want to enter.
Reading a single additional number into y.
Passing that single number into a function that expects an array.
There are numerous things wrong with this function; I think you need to map out what data needs to go where.

Related

Why can't I read a value from the user and make it a constant?

After inputting the following code, I would get an error.
const int quantity;
cout << "How much spacing do you want in-between the frames? " ;
cin >> quantity;
error: uninitialised const 'quantity'[-fpermissive]
error: ambiguous overload for 'operator>>'
This does not happen if I just use the type int
int quantity;
cout << "How much spacing do you want in-between the frames? " ;
cin >> quantity;
Which compiles without a problem. I'm new to C++ so I'd just like to know why this is.
If you define the variable as
const int quantity;
you're saying "I'd like an int called quantity, and under no circumstances do I want its value to ever change." As a result, if you then write
cin >> quantity;
the compiler says something to the effect of "wait - you want me to change the value of quantity by replacing it with whatever the user entered, but earlier you said that you never wanted me to change it!"
My sense is that you wanted to make it so that after you give an initial value to quantity that value never changes, but with const variables that initial value needs to be set when the variable is created. You could therefore try something like this:
const int quantity = readValue();
for some function readValue() that reads and returns an int value. That way, the compiler sees that quantity is given a fixed value, it knows that the value never changes, and you never try to directly cin into the value of quantity.
For a more technical perspective on the errors you got: when the compiler read
const int quantity;
without any value assigned to it, it reported an error because it's unusual to create a constant without giving it a value. (I can see from your code that you meant to give it a value, but the way you did it wasn't legal and the compiler didn't piece the two things together). The second error about operator >> resulted because none of the different ways that you can read something from cin (read a string, read an int, read a char, etc.) applied, since each of them assumed that they can get a mutable (modifiable) view of the value in question. Again, both of these issues stem from the fact that the compiler saw your code as two separate independent errors rather than one large "oops, that's not how const works" error.
You can initialize a const local variable only once, at the moment it's declared. Your example looks like it couldn't possibly work, but it's simple if you add a level of indirection.
int ReadAnInt()
{
int temp;
cin >> temp;
return temp;
}
const int quantity = ReadAnInt();
The const qualifier means that the variable is immutable and you cannot change its value. The first error is telling you that the variable is uninitialize.
cin allows you to assign a value to a variable, which immediately contradicts your const qualifier.
You must initialise quantity the moment you declare it. Furthermore, you can't assign a value to it later on; after all, it is constant.
First you put the same code in both of the boxes.
I admit you put the const symbol in the first source.
Second a const must be initialized at declaration in C++.
Thus you should put the code as following
int value;
cin >> value;
const int my_num = value;

Telephone directory program using 2D array in c++

I have been given following assignment
Write a simple telephone directory program; contain two dimensional arrays in which you have hard code names and telephone number. Then declare a simple character array. You have to prompt user to enter any name, which you want to search. This name should be store in this character array, then search this name from the two dimensional array. If number is found against entered name then program should display the number against this name, and if not found then program should display the message that name is not registered.
Here is my code but i could not get the number when i search for the name. I am new to coding so i am having trouble making this code work. Help is appreciated.
#include <iostream>
#include <conio.h>
using namespace std;
int getPhone(int p[5][10],int row, int col, char key[10],char n[5][10]);
int main() {
int i,j;
char search[10];
const int r = 5;
const int c = 10;
int element;
int phone[r][c] =
{
42-5429874,
42-5333156,
42-9824617,
42-9927562,
42-6238175
};
char name[r][c] = {"shazia","zara","sana","ahmad","maha"};
cout<<"\nEnter name to find in directory : ";
cin>>search[r];
element = getPhone(phone,r,c,search,name);
cin.get();
return 0;
}
int getPhone(int p[5][10],int row,int col,char key[10], char n[5][10]) {
int i, j;
for(i=0;i<row;i++)
for(j=0;j<col;j++)
p[5][10] = p[i][j];
if(key[j] = n[5][10])
cout<<"The desired number is: "<<p[i][j]<<endl;
else if(key[j]!=n[5][10])
cout<<"Sorry! This name is not registered.";
return p[i][j];
}
Your code contains several mistakes. Let's examine them.
for(i=0;i<row;i++)
for(j=0;j<col;j++)
p[5][10] = p[i][j];
Here, you make no change on your array, because just the value of p[5][10] is changed. Furthermore, you access an invalid memory zone, because array indexes go from 0 to size - 1 in C++. So last index is p[4][9].
if(key[j] = n[5][10])
In C++, comparing two values needs two =, because only one is an affectation that results the if to be always true. A tip to remember: two values to compare need two =.
else if(key[j]!=n[5][10])
The same than before, you access invalid memory zone. And are you sure that j is valid, e.g less than 10 ? If not, you do double invalid access.
cin>>search[r];
As search is an array of char, you do an input of only a single char there, which I think is not what you want and that can leads to segfault.
int phone[r][c] =
{
42-5429874,
42-5333156,
42-9824617,
42-9927562,
42-6238175
};
Your array is not good, a simple 1-dimension array is enough, not 2-dimensions. Furthermore, 42-54.. does a subtraction, and I think is not what you want.
There are others mistakes. But why not using C++ abstractions, like std::vector, or std::string? Your life would get so much easier. But I guess you have an old teacher that never took time to learn C++ news, or that is not a good teacher.
As a beginner, I suggest you to read C++ Primer and Programming: Principles and Practice Using C++ to introduce you both programming and modern C++.

Array Function. Would appreciate a little clarification

I have a question regarding a school lab assignment and I was hoping someone could clarify this a little for me. I'm not looking for an answer, just an approach. I've been unable to fully understand the books explanations.
Question: In a program, write a function that accepts three arguments: an array, the size of the array, and a number n.
Assume that the array contains integers. The function should display
all of the numbers in the array that are greater than the number n .
This is what I have right now:
/*
Programmer: Reilly Parker
Program Name: Lab14_LargerThanN.cpp
Date: 10/28/2016
Description: Displays values of a static array that are greater than a user inputted value.
Version: 1.0
*/
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
void arrayFunction(int[], int, int); // Prototype for arrayFunction. int[] = array, int = size, int = n
int main()
{
int n; // Initialize user inputted value "n"
cout << "Enter Value:" << endl;
cin >> n;
const int size = 20; // Constant array size of 20 integers.
int arrayNumbers[size] = {5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24}; // 20 assigned values for the array
arrayFunction(arrayNumbers, size, n); // Call function
return 0;
}
/* Description of code below:
The For statement scans each variable, if the array values are greater than the
variable "n" inputted by the user the output is only those values greater than "n."
*/
void arrayFunction(int arrayN[], int arrayS, int number) // Function Definiton
{
for (int i=0; i<arrayS; i++)
{
if (arrayN[i] > number)
{
cout << arrayN[i] << " ";
cout << endl;
}
}
}
For my whole answer I assume that this:
Question: In a program, write a function that accepts three arguments: an array, the size of the array, and a number n. Assume that the array contains integers. The function should display all of the numbers in the array that are greater than the number n .
is the whole assignment.
void arrayFunction(int[], int, int); is probably the only thing you could write. Note however that int[] is in fact int*.
As others pointed out don't bother with receiving input. Use something along this line: int numbers[] = {2,4,8,5,7,45,8,26,5,94,6,5,8};. It will create static array for you;
You have parameter int n but you never use it.
You are trying to send variable to the function arrayFunction but I can't see definition of this variable!
Use something called rubber duck debugging (google for it :) ). It will really help you.
If you have some more precise question, ask them.
As a side note: there are better ways of sending an array to the function, but your assignment forces you to use this old and not-so-good solution.
Would you use an if else statement? I've edited my original post with the updated code.
You have updated question, then I update my answer.
First and foremost of all: do indent your code properly!!!
If you do that, your code will be much cleaner, much more readable, and it will be much easier understandable not only for us, but primairly for you.
Next thing: do not omit braces even if they are not required in some context. Even experienced programmers only rarely omit them, so as a beginner you should never do so (as for example with your for loop).
Regarding if-else statement the short answer is: it depends.
Sometimes I would use if (note: in your case else is useless). But other times I would use ternary operator: condition ? value_if_true : value_if_false; or even a lambda expression.
In this case you should probably settle for an if, as it will be easier and more intuitive for you.
Aside from the C++ aspect, think about the steps you need to do to figure out if a number is greater than a certain value. Then do that for all the numbers in the array, and print out the number if it's greater than n. Since you have a 'for' loop, it looks like you already know how to do a loop and compare numbers in C++.
Also, it looks like in your arrayFunction you are trying to input values? You can't input a whole array's worth of values in a single statement like you appear to be trying (also, 'values' is not the name of any variable in arrayFunction, so that would not be recognized when you try to compile it).

Array causes stack overflow error

My program is this:
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
char choice;
int o,i,marks[i],ttlcredit=0;
double ttlGPA=0,finalGPA=0,credit[7][2],clsavg;
cout<<"Please enter what you want to calculate"<<endl;
cout<<"A for calculating Class Average GPA"<<endl;
cout<<"B for calculating a Specific GPA"<<endl;
cout<<"Your choice is? ";
cin>>choice;
cout<<endl;
if (choice == 'A'||choice == 'a')
{
cout<<"=========================================="<<endl;
cout<<" Class Average GPA"<<endl;
cout<<"=========================================="<<endl<<endl;
cout<<"Please enter the number of students in the class: ";
cin>>number;
for(i=0;i<number;i++)
{
cout<<"\nEnter student #"<<i+1<<"'s marks: ";
cin>>marks[i];
ttlGPA=ttlGPA+marks[i];
}
clsavg=ttlGPA/number;
cout<<"\nThe Average is: "<<clsavg<<endl;
}
else
{
}
}
It is half completed. When I build and run on CodeBlocks, an error instantly appeared:
I tried finding the source of error and I think that it is caused by the following in the code:
int o,i,marks[i],ttlcredit=0;
What makes me think so is because when I remove the [i] from marks[i], I will be not receive that error.
I think is stack overflow because I use Microsoft Visual Studio to help me debug and this is the error they gave me:
Unhandled exception at 0x0041419e in Project (1).exe: 0xC00000FD: Stack overflow.
My question is...
Is that the main cause of problem?
How do I resolve this issue?
You have to initialize the marks array with a positive length.
Get the number of students first, THEN create the array using that number.
Also, you need to declare the variable number.
As the other answers stated correctly, the problem is that int i is used uninitialized. However, the proposed fix
// initialze i
int marks[i];
is not standard C++, but only available through a compiler extension. In C++, the length of a built-in array must be a compile time constant. The better solution would be using std::vector:
// initialize i (better make it std::size_t instead of int)
std::vector<int> marks (i);
This will create a variable length array in a safe and standard conforming way.
First thing to say is that you simply shouldn't use arrays. They just are too weird in C and C++, and we have superior alternatives in modern C++.
Anyway, whether you use arrays or vectors, there are some important issues. Before discussing marks[i], it's simpler to look at credit[7][2] in this code.
int o,i,marks[i],ttlcredit=0;
double ttlGPA=0,finalGPA=0,credit[7][2],clsavg;
The dimensions are explicit in this declaration of credit. It's seven-times-two. Simple enough. You can read and write to credit[0][0] and credit[6][1] and many other values. But if you go outside the range, e.g. try to use credit[7][0], your program will compile and will probably appear correct for a while, but it could behave very badly and it is undefined how it will behave. It could decide to delete all the files on your computer, it is (seriously) entitled to do anything random and crazy. This is Undefined Behaviour.
Anyway, the really weird line is the declaration of marks.
int marks[i];
This definitely doesn't do what you think it does. It doesn't create an array that can be "indexed with arbitrary i". No, it allocates an array whose size is the initial value of i. But i is undefined at this stage so this is meaningless.
But i isn't relevant here anyway. How big do you want this array to be? The answer is number, isn't it? That is the number of people you'll store in your array.
So, a small improvement is to do this instead of int marks[i].
int marks[number];
But even this isn't correct. The value of number isn't set until the line cin >> number;, therefore you must declare int marks[number] after the line cin >> number; in order to ensure that marks has the correct size.
But, but, but, even after all this, we still don't have standard C++. It's OK to do int credit[7][2] because the size is fixed at compile time. You are normally not allowed to set the size of an array at runtime, e.g. int marks[number]. You might be able to use it if your compiler allows this extension (it's called Variable Length Array, from C).
So, this is not standard C++, and it's potentially very dangerous (see the Undefined Behaviour). What's the solution?
The solution is the standard solution for any problem involving arrays. Stop using arrays. (Really advanced programmers, in particular situations, might use std::array in modern C++, or even write their own clone of std:: array in older C++. But raw C [] arrays are to be avoided where possible.)
#include<vector>
int o,i,ttlcredit=0;
std::vector<int> marks;
marks is initially empty. We don't do cin >> marks[i];. Instead we use push_back to append new items to the end of the list.
int next_mark;
cin >> next_mark;
marks.push_back(next_mark);
Also, don't use marks[i] with a vector. It might look OK, but it is dangerous. Better to use marks.at(i) to read or write the element. at will do bounds checking for you, giving you a proper error message if i is too small (less then 0) or too big for the size of the vector.
int o,i,marks[i],ttlcredit=0;
i is not initialized. initialize i first.
If you are not sure of the size of the array, allocate it dynamically.
use new
refer this link on how to use new - cpluspluss

c++ read numbers from text into integer array, calculate average

I'm struggling with a class assignment. I've tried writing this several ways, I'm extremely confused.
Assignment:
Read in ten integer values from a from a file, and store them in an
array or vector. The program you will write will read and store the
last ten values read from a temperature gauge. The reading of the
values should be done in a separate function that takes an integer
array as a parameter, and read from a file named tempInput.txt:
example: void readData(int tempArray[]) The file numbers will be on
consecutive lines. Then, from main, you will call another function,
whose signature and return type is thus: bool isDangerous(int
tempArray[]); The function is dangerous will sum the values in the
tempArray and divide by 10 storing the result (average) in another
variable of the appropriate data type. Then, if the temperature is
greater than 100, the function should return true. if it is 100 or
less, it should return false. in main, you should use the function in
a way such that you print: the temp is ok (if return false) or, the
temp is too hot (if > 100)
If I write a function readData(int array[]) then I must already an array to pass as the argument.
But, the entire purpose of this function is to read from file, THEN create the array. Do I need to write a placeholder temp. array?
Do I need to make the array a string then parse to int or double?
My non-working start is:
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
//prototypes
void readTemp();
int main()
{
int allTemp[10];
readTemp();
}
void ReadTemp()
{
ifstream in_File;
int inNumbers[10];
double average;
in_File.open("tempInput.txt");
for(int i = 0; i < 10; ++i)
{
in_File>>inNumbers[i];
average = inNumbers[i++]/i;
}
cout<< average <<endl;
}
Thanks for any tips. I couldn't get the file read in working so I haven't started on the function that will average the data and return bool.
"entire purpose of this function is to read from file, THEN create the array"
No! You have to have an array beforehand. Either it's big enough, to read in all the data from file, or you have to use dynamic memory management.
Better though, you use some appropriate container like std::vector<int> to receive the data while reading from the file.