I don't understand how the following code can work.
void read(int *);
int numbers[10];
fstream myfile;
int main() {
myfile.open("input.txt", ios::in);
read(numbers);
for (int i = 0; i < 10; i++) {
cout << numbers[i] << endl;
}
}
void read(int *z) {
// is my understanding correct that *z is an pointer to the first element of the array?
for (int i = 10; i > 0; i--) {
myfile >> *z++; // why can write characters into an int array?
}
}
my_file has
basic_fstream<char>
as datatype.
however in the read function, it's values are written into an int array.
Related
The Function won't initiate can someone help? When I run it in the debugger program skips over function and I don't know why?
#include <iostream>
using namespace std;
int size_array= 0;
int *data_array;
void sorting(int *[], int);
int main()
{
cout<<"enter in array size \n";
cin>>size_array;
int *data_array=new int(size_array);
for(int i=0;i<size_array;i++)
{
cout<<"enter number "<<i+1<<endl;
cin>>data_array[i];
}
**int sorting(int data_array, int size_array);**
for (int i=0; i<size_array;i++)
{
cout<<data_array[i]<<endl;
}
return 0;
}
The marked code is simply declaring the function, not calling it.
Also, your data_array is a pointer to a single int whose value is initialized as size_array. But you want an array of size_array number of ints instead.
Try this:
#include <iostream>
using namespace std;
void sorting(int[], int);
int main()
{
int size_array = 0;
cout << "enter in array size \n";
cin >> size_array;
int *data_array = new int[size_array];
for(int i = 0; i < size_array; i++)
{
cout << "enter number " << i+1 << endl;
cin >> data_array[i];
}
sorting(data_array, size_array);
for (int i = 0; i < size_array; i++)
{
cout << data_array[i] << endl;
}
delete[] data_array;
return 0;
}
void sorting(int data_array[], int size_array)
{
// sort data_array as needed...
}
This question already has answers here:
How do I use arrays in C++?
(5 answers)
Closed 1 year ago.
When inputting a array in c++ the element in 0th position will become the length of the array.
have two functions to input and print the array when print function calls the output array has always the array length in 0th position.
#include<iostream>
using namespace std;
int getArray(int array[])
{
int len;
cout << "Enter the length of the array" << endl;
cin >> len;
cout << "Enter the elements in the array" << endl;
for (int i = 0; i < len; ++i)
{
cin >> array[i];
}
return len;
}
void printArray(int array[], int len)
{
for (int i = 0; i < len; i++)
{
cout << array[i];
}
}
int main(int argc, char const *argv[])
{
int array[] = {};
int len = getArray(array);
printArray(array, len);
return 0;
}
In C++, the size of an array must be a compile time constant. So you cannot write code like:
int n = 10;
int arr[n]; //incorrect
Correct way to write this would be:
const int n = 10;
int arr[n]; //correct
For the same reason the following code (last statement) is incorrect :
int k;
cin >> k;
int arr[k]; //incorrect because k must be a compile time constant
You can see that this results in a problem here.
You should use std::vector for this purpose.
Using std::vector, your implementation would look like:
#include<iostream>
#include <vector>
using namespace std;
//passing vec by reference
int getArray(std::vector<int> &vec)
{
int len;
cout << "Enter the length of the vector" << endl;
cin >> len;
cout << "Enter the elements in the vector" << endl;
int element;
for (int i = 0; i < len; ++i)
{
cin >> element;
vec.push_back(element);//use push_back to add element to vector
}
return len;
}
//passing vec by reference
void printArray(std::vector<int> &vec, int len)
{
for (int i = 0; i < len; i++)
{
cout << vec[i]<<std::endl;//use vec[i] to access ith element
}
}
int main()
{
std::vector<int> vec;
int len = getArray(vec);
printArray(vec, len);
return 0;
}
You can see the output here.
Note
You can simply take the input in the main() itself instead of calling another functions. Similarly for printing the vector. But i have given the code according to your implementation.
#include<iostream>
#include<fstream>
using namespace std;
int *elementShifter(int[], int);
int main()
{
int SIZE = 50;
int array[SIZE];
ifstream infile("Gradelist.txt");
if (!infile)
{
cout << "File not found" << endl;
return -1;
}
int count = -1,data=0;
while (!infile.eof())
{
count++;
if (count < 0 || count > 50)
return -1;
else
{
infile >> array[count];
}
cout << array[count] << endl;
}
cout << endl;
int *s=elementShifter(array, count);
for (int i = 0; i <=count; i++)
{
cout << *s << endl;
s++;
}
return 1;
}
int *elementShifter(int arr[], int size)
{
int *newArr = new int[size + 1];
newArr[0] = 0;
for (int i = 0; i < size; i++)
{
newArr[i+1]=arr[i];
}
return newArr;
}
I just cannot figure out why i am getting this number here
This is reworked into slightly more idiomatic C++, but there's stuff here that might not fly in whatever course you're in, so adapt accordingly:
#include<iostream>
#include<fstream>
// using namespace std; is a bad habit to get into, that prefix
// exists for an important reason: Code separation
// Tip: If you define before you reference a function in your code,
// there is no need for a separate declaration.
// Note use of const on arguments that are not mutated
void unshift(int*& array, size_t& size, const int elem) {
int *resized = new int[++size];
// Insert at the start of the array
resized[0] = elem;
// Copy the remainder
for (int i = 1; i < size; ++i) {
resized[i] = array[i-1];
}
// Don't forget to release the old memory or you have a leak
delete[] array;
// Since the pointer is passed in as a reference, easy to swap it
array = resized;
}
int main() {
size_t size = 1; // size_t is often used for "size"-type args
int *array = new int[size];
std::ifstream infile("Gradelist.txt");
if (!infile) {
// Use std::cerr for errors.
std::cerr << "File not found" << std::endl;
return -1;
}
// infile evaluates as true so long as it has data to read.
while (infile) {
// You already have a count, it's "size"
if (size> 50) {
return -1;
}
int input;
infile >> input;
// This function takes mutable arguments, so they change via
// references.
unshift(array, size, input);
}
std::cout << std::endl;
for (int i = 0; i < size; ++i) {
std::cout << array[i] << std::endl;
}
// Take out the trash
delete[] array;
// Return zero on success, non-zero on failure.
return 0;
}
Of course a lot of this code goes away if you can use std::vector<int> and push_back(), but if you need to learn how to do this at a low-level, here you are with pointers and all the mess they create.
The goal in modern C++ is to avoid using pointers and instead lean heavily on the Standard Library to help you out.
I want to create a function which generates an array(filled with random numbers) of the size I give as an input and the function returns the address of the first element of the generated array. I wrote the code as best as possible without any errors or warning. But at the runtime, the program crashes. I try to debug it but the debugger also froze and do nothing. I think the problem is in returning the pointer. Please help.
#include<iostream>
#include<cstdlib>
using namespace std;
int** the_gen(int num)
{
srand(1000);
int *ptr= new int(num);
int** const dptr=&ptr;
for(int i=0;i<num;i++)
{
*ptr= rand();
ptr++;
}
return dptr;
}
int main()
{
cout<<"Size of array:"<<endl;
int size_of_array;
cin>>size_of_array;
int **a;
a=the_gen(size_of_array);
for(int i=0;i<size_of_array;i++)
{
cout<<**a<<",";
a++;
}
}
you were using int** unnecessarily. only need to use that if you're creating an array of int pointers or a 2d array of int's:
the following code does what you're after i think:
#include<iostream>
#include<cstdlib>
using namespace std;
int* the_gen(int num)
{
srand(1000);
//edit
int *ptr = new int[num];
int* const dptr = ptr;
for (int i = 0; i < num; i++)
{
*ptr = rand();
ptr++;
}
return dptr;
}
int main()
{
cout << "Size of array:" << endl;
int size_of_array;
cin >> size_of_array;
int *a;
a = the_gen(size_of_array);
for (int i = 0; i < size_of_array; i++)
{
cout << *a << ",";
a++;
}
}
I think returning pointer is always bad idea, we should take memory pointers as a parameter as the follow
void the_gen(int num, int** arry)
{
srand(1000);
int *ptr = new int[num];
*arry = ptr;
for (int i = 0; i < num; i++)
{
ptr[i] = rand();
}
}
int main()
{
cout << "Size of array:" << endl;
int size_of_array;
cin >> size_of_array;
int *a;
the_gen(size_of_array, &a);
for (int i = 0; i < size_of_array; i++)
{
cout << a[i] << ",";
}
}
I need to calculate numbers from the array.
I have a code written but I don't know how exactly I would need to write that I could get a summation of the numbers in the array.
If You would recommend some good material to learn something like so of, I would be thankful.
#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;
int n;
int array_1[20];
const char D[]= "Data.txt";
const char R[]="Rezults.txt";
void to_read ( int &n, int array_1[])
{
ifstream fd(D);
fd>>n;
for (int i=0; i<n; i++)
fd>>array_1[i];
fd.close();
}
int to_sum()
{
int m=0;
for (int i=0; i<n; i++)
m=m+array_1[i];
return m;
}
void to_print(int n, int mas_1[])
{
int sum=0;
ofstream fr(R);
fr<<n<<endl;
for (int i=0; i<n; i++)
fr<<array_1[i]<<" ";
fr<<endl;
sum=to_sum();
fr<<sum<<endl;
fr.close();
}
int main()
{
to_read(n, array_1);
to_sum();
to_print(n, array_1);
return 0;
}
I rewritten your code, removed global variables, changed formatting for easier reading, rename some variables to more explain for what they are and add function prototypes. Hope this will help you a little.
There are still lot of places which should be changed, but i want to keep as close to your original code as possible.
If you have any questions feel free to ask.
#include <iostream>
#include <fstream>
using namespace std;
//functions prototypes (these will be moved to header file if you wanna use this code from another file)
void to_read(int &len, int * array, const char * name); //added name parameter to avoid glogal variables
void to_print(int len, int * array, const char * name);
int to_sum(int len, int * array); //added parameters to avoid global variables
int main()
{
int lenght = 20; //moved to here, try to avoid global variables
int array_1[lenght]; //preconfigured size depend on variable
const char D[] = "Data.txt";
const char R[] = "Rezults.txt";
to_read(lenght, array_1, D);
//to_sum(lenght, array_1); //not needed here, not storing/processing result
to_print(lenght, array_1, R);
return 0;
}
void to_read(int &len, int * array, const char *name)
{
int lenght;
ifstream fd(name); //you should check if opening was successful
fd >> lenght; //you should check if reading was successful
if (lenght < len) len = lenght; //to prevent overflow of array, read max 20
for (int i=0; i<len; i++){
fd >> array[i];
}
fd.close();
}
int to_sum(int len, int * array)
{
int sum=0;
for (int i=0; i<len; i++){
sum += array[i]; //changed sum = sum + value; to sum += value; its same but this is more often used
}
return sum;
}
void to_print(int len, int * array, const char *name)
{
int sum = to_sum(len, array);
ofstream fr(name);
fr << len << endl;
for (int i=0; i<len; i++){
fr << array[i] << " ";
}
fr << endl;
fr << sum << endl;
fr.close();
}