I'm new to the site. I'm sorry for my missing. When I call the print_array function it gives an error. I do not understand why this is happening. Could you please help me?
Thank you for answers.
#include <iostream>
using namespace std;
void print_array(int n,int m,int matrix[][m]){
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
cout << matrix[i][j];
}
cout << "\n";
}
cout << "\n";
}
int main() {
int m,n;
while (true){
cout << "Given row size: " ;
cin >> n ;
cout << "Given column size: ";
cin >> m;
if (m>=5 && n>=5){
break;
}
else{
cout <<"Row and Column size must be grater than 5. Please try again"<<endl;
continue;
}
}
int array_A[n][m];
cout <<"Enter elements by giving a space between them\n"<<endl;
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
cin >> array_A[i][j];
}
}
cout << "\n";
print_array(n,m,array_A);
return 0;
}
I think your understanding of array allocation is a bit wrong. In C++, you can't just dynamically allocate memory for an array as you did with int array_A[n][m]. You either have to allocate memory manually using the keyword new or use a container that does this for you, like std::vector. Since you are starting I'd go with the standard library container.
You could initialize your variable with something like std::vector<std::vector<int>> array_A(n, std::vector<int>(m, 0)) after including #include <vector>. After this, you could simply use your variable as you did and pass it as a parameter of your function.
Related
I am trying to implement random_function(), which outputs the amount of random numbers within a range (user input), and count_function() to count for the value that the user wants to look up in the outputted random numbers. I made the random numbers to be saved in an array called randomlist[] so that it can be used to count for the value from the outputted random numbers. However, I cannot declare an array without its fixed size in the header file and define its size in the count_function.cpp. So I cannot use randomlist[] in the count_function() without redefining it (which is meaningless...).
Is there a way to declare array without defining its size, in the header file?
Here is the source code:
header file:
#pragma once
using namespace std;
class Rand
{
public:
// Rand();
int range,min,max;
char key;
void Random_function();
void Count_function();
// randomlist[]; something like this, which that is not possible in c++
};
This is randomfunction.cpp:
#include <iostream>
#include "random_function.hpp"
using namespace std;
void Rand::Random_function()
{
beginning:
cout << "Enter amount of numbers to generate: ";
cin >> range;
if (range<=0 || cin.fail())
{
cout <<"Error! Please enter valid number and try again! "<<endl;
goto beginning;
}
else
{
reenter:
cout << "Enter minimum boundary: ";
cin >> min;
cout << "Enter maximum boundary: ";
cin >> max;
cout << "\n";
srand((unsigned)time(NULL));
if(max<min || cin.fail())
{
cout << "\nError! Please enter the valid value and try again! " << endl;
goto reenter;
}
else
{
int randomlist[range]; //I defined the size of the randomlist here but I want to use this outside of the random_fucntion() as well.
for(int i=0 ; i < range; i++)
{
randomlist[i] = min + (rand() % static_cast<int>(max - min + 1));
cout <<i+1<<". "<< randomlist[i] <<endl;
}
}
cout <<"\n"<< "Total random numbers generated: " << range<< endl;
cout <<"Do you want to continue? y/n"<<endl;
cin >> key;
if(key=='y')
{
Count_function();
cout <<"Do you want to restart? y/n"<<endl;
cin >> key;
if(key=='y')
{
goto beginning;
}
else
{
exit(0);
}
}
else
{
cout <<"Do you want to restart? y/n"<<endl;
cin >> key;
if(key=='y')
{
goto beginning;
}
else
{
exit(0);
}
}
}
}
void Rand::Count_function()
{
int n,count=0;
reenter2:
cout<<"Enter the value to count for: ";
cin>>n;
if(cin.fail())
{
cout<<"Please enter valid value to count for"<<endl;
goto reenter2;
}
else
{
for(int i=0 ; i <range; i++)
{
if(randomlist[i]==n)
{
count++;
}
}
}
cout <<"The number of '"<<n<<"'s in the given list is: "<< count <<endl;
}
main:
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <random>
#include "random_function.hpp"
using namespace std;
int main()
{
Rand call;
call.Random_function();
}
When you want to use an array, but the size cannot be known at compile-time, the generally accepted approach in C++ is to use a std::vector.
I was given a C++ assignment for my class to make a program that reads student data records from a user, and the program will then sort the keyed in data records into sorted order in terms of students’ GPAs, or in terms of the alphabetical order of the students' last names, or doing both, depending on the user’s option. The framework was given to me by my professor.
I'm having difficulties with vectors and strings, and getting these to work in my given program. I keep receiving the following errors:
no matching function for call to ‘std::vector::push_back(std::string&)’
no matching function for call to ‘std::vector::push_back(float&)’
I've included my full code below and would greatly appreciate if somebody could give it a look. I understand that something needs to be changed for v.push_back(); to work, but I'm not sure about the exact change I should make. I'm very new to C++ and have a limited understanding of strings and vectors.
Thank you so much in advance!
#include <iostream>
#include <cctype>
#include <string>
#include <cstring>
#include <vector>
using namespace std;
struct student
{
string name;
float gpa;
};
std::vector <student> v;
void input_data(std::vector<student> &v);
void output_data();
void swap(student *std1, student *std2);
void sort_gpa_asc();
void sort_gpa_des();
void sort_name();
void show_data();
int num;
int main()
{
char option;
v.push_back(student{"Dana", 3.6});
input_data(v);
cout << "Your options for sorting (key in 'G' to sort students' data in terms of gpa in" << endl
<< "both ascending and descending order; key in 'A' to sort students' data in terms of" << endl
<< "alphabetical order of students' last name; key in 'B' for both types of sorting): ";
cin >> option;
int num;
if (option == 'G')
{
sort_gpa_asc();
sort_gpa_des();
}
else if (option == 'A')
{
sort_name();
}
else if (option == 'B')
{
sort_gpa_asc();
sort_gpa_des();
sort_name();
}
else
cout << "Incorrect option!" << endl;
return 0;
}
void input_data(std::vector<student> &v)
{
string names;
float grade_point_average;
int num;
v.push_back(student{"Dana", 3.6});
cout << "Enter the number of students: ";
cin >> num;
for(int i=0; i < num; i++){
cout << "Enter student's name (write the surname before the first name): ";
cin.get();
getline(cin, names);
v.push_back(names);
}
for(int i=0; i < num; i++){
cout << "Enter student's GPA: ";
cin >> grade_point_average;
v.push_back(grade_point_average);
}
for(int i=0; i < v.size(); i++){
cout << v[i].gpa;
}
for(int i=0; i < v.size(); i++){
cout << v[i].name;
}
cin.get();
cin.get();
}
void swap(student *std1, student *std2)
{
}
void sort_gpa_asc()
{
}
void sort_gpa_des()
{
}
void sort_name()
{
}
void show_data()
{
}
Your vector has a type std::vector<student>
But you are trying to push a string instead:
string names;
v.push_back(names);
You probably meant v.push_back(student{names, 0});
This however opens another issue with pushing the GPA. Here you should just iterate over existing elements:
for(int i=0; i < num; i++){
cout << "Enter student's GPA: ";
cin >> grade_point_average;
v[i].gpa = grade_point_average;
}
I would also advise you to use emplace_back instead of push_back as a more efficient alternative:
//v.push_back(student{"Dana", 3.6});
v.emplace_back("Dana", 3.6);
you can use vector::push_back requires the template type of your vector in you case
vector<student>::push_back(student);
the code you should use is something like this
v.push_back(student(constructor arguments))
or
student s = {.name = "name", .gpa = x};
v.push_back(s);
i think the vector v is type student, but not string or float, thus it occurs error.
I have a structure sportist
struct sportist{
string name;
string surname;
int goals;
string tim;
}
Here is the function that should read the values.
void read(sportist x[],int n)
{
int i;
for(i=0;i<n;i++)
{
cout<<"************************************************"<<endl;
cout<<"Name:";
cin>>x[i].name;
cout<<endl<<"Surname:";
cin>>x[i].surname;
cout<<endl<<"Goals :";
cin>>x[i].goals;
cout<<endl<<"Name of the team:";
cin>>x[i].tim;
}
My question is how can I use pointers, because I need to? My attempt:
void read(sportist* x,int n)
{
int i;
for(i=0;i<n;i++)
{
cout<<"************************************************"<<endl;
cout<<"Name:";
cin>>x->name;
cout<<endl<<"Surname:";
cin>>x->surname;
cout<<endl<<"Goals :";
cin>>x->goals;
cout<<endl<<"Name of the team:";
cin>>x->tim;
}
}
What I want is to sort the sequence of athletes and teams by the number of goals and print them on the screen to sort them in a popup order. But it shows me errors when I debug.
you should pay attention to one point when you are using array x[i] with i increasing ,you are traversing the array ,but with pointer you should move pointer so it would point to next elements of array.You should use x++;.
look:
void read(sportist* x, int n)
{
int i;
for (i = 0; i < n; i++)
{
cout << "************************************************" << endl;
cout << "Name:";
cin >> x->name;
cout << endl << "Surname:";
cin >> x->surname;
cout << endl << "Goals :";
cin >> x->goals;
cout << endl << "Name of the team:";
cin >> x->tim;
x++;
}
}
if you miss x++; each time you will write entered data in first element of array.
Also note in function you are declaring this array of sportist , if you declare sportist* x instead of sportist x[num] ,you have to allocate memory for it too.
please, why this pointer array won't accept more than 5 values?
Doing excercises from Prata's C++ book, but got stuck on this.
//ex2_numrow -- showing entered numbers til zero is entered
#include <iostream>
using namespace std;
int main()
{
int n = 0;
int num = 0;
int* entered = new int[1];
do
{
cout << "Enter number: ";
cin >> num;
entered[n] = num;
cout << "Your numbers: ";
for (int i = 0; i <= n; i++)
{
cout << entered[i] << " ";
}
cout << endl << endl;
n++;
} while (num);
delete[] entered;
return 0;
}
The code int* entered = new int[1]; gives you a pointer to an array of size one!
It is very unwise (i.e., undefined behaviour) to then try to write values outside of that array. The best case is that your code will crash before it causes any serious issues.
As an aside, the set of use cases for raw pointers is fast dwindling in C++, you should generally be looking at smart pointers instead.
I say "generally" because, if your intent is to have a resizable array, even smart pointers won't help that much. What will help is a little thing I like to call std::vector :-) You should probably look into using that for your immediate purpose.
For example, this program accepts positive numbers, adding them to a vector, then printing them out:
#include <iostream>
#include <vector>
int main() {
std::vector<int> numbers;
int num;
do {
std::cout << "Enter number: ";
std::cin >> num; // should probably check for errors in real code
if (num >= 0) {
numbers.push_back(num);
}
} while (num >= 0);
std::cout << "You entered:";
for (int num: numbers) {
std::cout << ' ' << num;
}
std::cout << '\n';
}
I would like to pass dynamic arrays to functions and receive user input. Currently I'm using the following code:
#include <iostream>
using namespace std;
struct make
{
int part;
int graph;
int like;
};
int z;
int *p = new int [z];
void inpart( make x[],int *fig)
{
cout << "Input part\n";
cin >> x[*fig].part;
}
void ingraph(make x[],int *tig)
{
cout << "Input graph\n";
cin >> x[*tig].graph;
}
void inlike(make x[],int *gig)
{
cout << "Input like\n";
cin >> x[*gig].like;
}
int main()
{
cout << "Input array count\n";
cin >> z;
make p[z];
for (int i=0; i < z; i++)
{
inpart(p,&z);
ingraph(p,&z);
inlike(p,&z);
}
for (int i=0; i < z; i++)
{
cout << "the result is\n";
cout << p[z].part << ", ";
cout << p[z].graph << ", ";
cout << p[z].like << "\n";
}
}
My input 1,1,1 for all the structure objects should output 1,1,1. However, the answer I receive is 1,0,2. Why?
Firstly, you shouldn't trying to initialize a static buildin array in run-time:
Your implementation is wrong here:
cout<< "Input array count\n";
cin>>z;//initialized in run-time
make p[z]; // wrong, need to be allocated with new
make* example = new make[z]; // Ok!
Secondly, you're trying to read and write out of bounds of the created array. It's Undefined behaviour. When you're creating an array with size N, chunk of the memory will be allocated to which you can have access by index. In your case from 0 to z or [0,z), excluding z. To sum up, your cycle should look like this:
for (int i = 0; i < z; i++) {
inpart(p,&i);
ingraph(p,&i);
inlike(p,&i);
}
Actually u've made a lot of mistakes in your code, but I feel like you will understand this later when continue learning.