#include <iostream>
usingnamespace std;
int main()
{
int size=0;
float weight[size];
std::cout<<"Enter number of students of school schildren : ";
std::cin>>size;
std::cout<<"Enter weight of students for "<<size<<" school schildren : "<<endl<<endl;
for (int i = 0; i < size; i ++)
{
std::cout<< i + 1 << ": ";
std::cin>>weight[i];
}
std::cout << "\nWeights : "<<endl<<endl;
for (int i = 0; i < size; i ++)
{
std::cout<< i + 1 << ": " << weight[i]<<endl<<endl;
}
system ("PAUSE");
return 0;
}
Line 8 requires that size is a constant. To do anything useful, size should be greater than zero.
try lines 7 and 8
7 8
constint size = 50;
float weight[size];
at line 11, the value input should be no greater than the previously specified size. You will have to use a separate variable for this, as size is a constant.
#include <iostream>
#include <vector>
usingnamespace std;
int main()
{
int size=0;
vector <float> weight;
std::cout<<"Enter number of students of school schildren : ";
std::cin>>size;
weight.resize(size);
std::cout<<"Enter weight of students for "<<size<<" school schildren : "<<endl<<endl;
for (int i = 0; i < size; i ++)
{
std::cout<< i + 1 << ": ";
std::cin>>weight[i];
}
std::cout << "\nWeights : "<<endl<<endl;
for (int i = 0; i < size; i ++)
{
std::cout<< i + 1 << ": " << weight[i]<<endl<<endl;
}
system ("PAUSE");
return 0;
}
Often, the vector size is not specified, but instead is allowed to grow as necessary, like this:
#include <iostream>
#include <vector>
int main()
{
int size=0;
std::vector <float> weight;
std::cout<<"Enter number of students of school schildren : ";
std::cin>>size;
std::cout<<"Enter weight of students for "<<size
<<" school schildren : "<<std::endl<<std::endl;
for (int i = 0; i < size; i ++)
{
std::cout<< i + 1 << ": ";
float w;
std::cin >> w;
weight.push_back(w);
}
std::cout << "\nWeights : "<<std::endl<<std::endl;
for (int i = 0; i < weight.size() ; i ++)
{
std::cout<< i + 1 << ": " << weight[i]<<std::endl<<std::endl;
}
std::system ("PAUSE");
return 0;
}
actually, in my course university syllabus, vector and pointer are in semester 2..
i'm now in semester 1...
my lecturer says that we can use array size defined by user without using vector and pointer. but, he doesn't want to teach us how to use the alternatif way.
thus, as conclusion, i only use pointer and vector...
In standard C++, the size if an array must be a constant known at compile time. If the size is to be chosen by the user, then you should use something like this: float * weight = newfloat [size];
and when processing is finished, release the memory with delete [] weight;
The original method (at the start of this thread) will not compile as standard C++, but some compilers will permit it.