c++ - Converting char dynamic array atoi to int -


i had text file having 15 numbers , last number 15. and, wanted read in, steps did:

  • first, tried count how many numbers in txt file.
  • accordingly, created dynamic size array.
  • tried save numbers dynamic array corresponding indices.

now, my question is, since, i'm reading numbers txt file in form of character strings. therefore, how convert char int dynamic array. and, algorithm i've used, producing garbage values on terminal while converting int. couldn't figure out wrong it.

my code:

#include <iostream> #include <fstream>  using namespace std;  int main(int argc, char* argv[]) {     char *nptr = argv[1];     char *buffer = new char[5];     int index = 0;      ifstream fin(nptr); //open file      if (argc > 1)     {         // allocate memory         if (!fin)         {             cout << "can't read file!!" << endl;             return -1;         }          if (fin)         {             cout << "open sucessues!! " << endl;         }          while (!fin.eof())         {             fin >> buffer;             index++; //counting here!!!         }          cout << "index: " << index << endl; //print out counting results!         cout << "buffer: " << buffer << endl; // checking 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;          (int = 0; < index; ++i)         {             cout << *number << endl; //*number print out garbage, don't know why!             number++;         }         fin.close();     }     return 0; } 

garbage output:

open sucessues!!   index: 15 buffer: 15 0 1073741824 0 1073741824 2136670223 32767 -1680479188 32767 0 0 0 0 0 0 0 

you missed '\0' in buffer. make buffer size + 1 , add \0 @ it's end, garbage must go away.


Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -