So I am trying to teach myself programming and I am really beginning to grasp c++ but there is a practice exercise I don't understand.
I was hoping somebody could start the code off for me?
This is what I have so far.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
//Practice
//
#include <fstream>
#include <iostream>
int main ()
{
system("pause");
return 0;
}
Hints:
1.Input a sting from user as the file-name,open it.
2.Read the first line using getline() , or since you know its a number use extraction operator.
1 2
int array_size ;
file >> array_size;
3.For a dynamically sized array , you can use std::vector , but I suspect you are not supposed to here.
So allocate memory from the free-store or heap:
1 2 3
double *my_array = newdouble[array_size];
//do whatever with the array.
delete[] my_array;//give it back,otherwise it may cause a memory leak in the application
#include <fstream>
#include <iostream>
usingnamespace std;
int main ( )
{
char filename [30]; // char array to hold file name
cout << ( "Please enter the file name: " ); // you forgot a semicolon here
cin.getline ( filename, 30 );
// this creates a double array of size 100
double *my_array = newdouble[100];
// this deletes the dynamically created array
delete [] my_array;
}
thank you for the help everyone! This is what I have so far but I am getting an error message. "error message: error allocation 834349034 bytes" Any ideas what I am doing wrong?
Your problem is you're trying to read from a file that doesn't exist. You need a file to read from if you're going to try to put information from a file into a variable.
Thanks for going back and forth with me Pindrought. I copied the code above ou gave me and i am still getting that error message. Should I change the word "filename" to the "numbers" file?
line 8: 30 specifies the number of characters in that array. filename is an array of 30 characters.
line 13: should be cin.getline(filename,29)
This will attempt to read 29 characters from cin into filename. It doesn't name any files, it just gets a string of characters. It needs to be 29, not 30, because c-strings have to have a null terminator. That is, the last character has to be '\0'. To make sure that this is true...
line 8: you should change this to char filename [30] = { 0 };
This will set every character in the array to the null character.