////////// new update!!!!! //////////
.txt have 15 numbers , last number is "15" 1. i try to count how many(save into my index) of numbers in my .txt file. 2. create my dynamic array size with the index. 3. save all the number into my dynamic array.
question: how to cover the char dynamic array to int dynamic array.
i got garbage output in my terminal:
Open sucessues!!
index: 15
buffer: 15
0
1073741824
0
1073741824
2136670223
32767
-1680479188
32767
0
0
0
0
0
0
0
int main(int argc, char* argv[])
{
char *nPtr = argv[1];
char *buffer = new char[5];
int index = 0;
ifstream fin(nPtr); //open the file
if (argc > 1){
// allocate the memory
if(!fin){
cout << "can't read the file!!" << endl;
return -1;
}
if(fin){
cout << "Open sucessues!! " << endl;
}
while (!fin.eof()){
fin >> buffer;
index++; //counting here!!!
}
cout << "index: " << index << endl; //print out the counting results!
cout << "buffer: " << buffer << endl; // checking the last number! should "15"
delete[] buffer; //
buffer = NULL;
int *number = new int[index];
char *temp = new char[index];
int *home = number; //home
while(!fin.eof()){
fin >> temp;
*number= atoi(temp); //im confessing right here!!!
number++;
temp++;
}
number = home;
for (int i = 0; i < index; ++i)
{
cout << *number << endl; //*number print out garbage, i don't know why!
number++;
}
fin.close( );
}
return 0;
}
/////************
//////// old ///////// don't read /////i am wondering how to use argc and argv to read a file: numbers.txt(few numbers inside). my goal is: read a file with my ./sort in terminal like: ./sort numbers then use buffer and index to count how many number inside, use index to create dynamic array, finally i read the file again, but change all the "number" to int by using atoi.
i got the Segmentation fault: 11 after i type: ./sort numbers in my terminal.
can anyone help me here? i need those array to sort my number. here i got so far:
int main(int argc, char* argv[])
{
char *nPtr = argv[1];
char *buffer[3];
int index = 0;
ifstream fin(nPtr); //open the file
// allocate the memory
if(fin.is_open()){
cout << "open" << endl;
while(!fin.eof()){
fin >> *buffer;
index++;
}
cout << index << endl;
}