Like Tree5Likes
  • 1 Post By laserlight
  • 1 Post By laserlight
  • 3 Post By Salem

Not able to read data from text file and convert it to integer

This is a discussion on Not able to read data from text file and convert it to integer within the C++ Programming forums, part of the General Programming Boards category; Hi, I am trying to read an array values from Tmin.txt file. I take array size from user viz. number ...

  1. #1
    Registered User
    Join Date
    Mar 2013
    Posts
    5

    Question Not able to read data from text file and convert it to integer

    Hi,

    I am trying to read an array values from Tmin.txt file. I take array size from user viz. number of raw & column and then, read the following data from Tmin.txt file which look like this:

    20 40 20 25 30

    20 30 40 20 25

    20 40 20 25 30

    20 30 40 20 25

    30 40 40 30 40

    i am using getline, and then converting it to int by using atoi. But my code is not working. can somebody help me out on this.

    Code :

    Code:
    // reading a text file
    #include <iostream>
    #include <fstream>
    #include <string>
    
    
    using namespace std;
    
    
    int main () {
    
    
     string line;
     int i,j,c;
     int Ncoil, Ntank;
     int **Tmin;
     string **Tminstring;
     char str[256];
    
    
     cout << "Number of coils to be cleaned: ";
     cin >> Ncoil;
    
    
     cout << "Number of tanks: ";
     cin >> Ntank;
    
    
    Tmin = new int *[Ncoil];
    
    
     for (int i = 0; i <= Ncoil; ++i)
         {
             Tmin[i] = new int[Ntank];
             for(int j = 0; j <= Ntank; ++j)
                {
                 ifstream myfile ("Tmin.txt");
                    if (myfile.is_open())
                    {
                        while ( myfile.good() )
                            { 
                                getline(myfile, line, ' ');
                                c = atoi(line);
                                Tmin[i][j] = c; 
                                myfile.close();
                            }
                    }
                    else cout << "Unable to open output file";
                 }
         }
      return 0;
    }

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,447
    For starters, change your code to make use of std::vector or some other suitable container instead of performing manual memory management.

    Next, open the file once, not on each iteration of the loop. Then, use the return value of getline, not good(), to control the inner loop.

    In the inner loop, since the line has more than one integer, yet it is a known number of them, initialise a stringstream with the line, then use operator>> to extract the integers.
    Elysia likes this.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User Vespasian's Avatar
    Join Date
    Aug 2011
    Posts
    181
    First, you need to include the standard library as atoi is defined within the stdlib: #include <stdlib.h>

    Secondly, I believe the atoi function works on C style strings which are character array's and not C++ style string class. Because of this, add in line 44 a conversion from your C++ string class to a c style string using the c_str() function. Then pass that converted string, called cstr, to the atoi function. In other words, cstr (converted C character array) = line (C++ string instance).

    Below compiles fine (added in comments where changed):


    Code:
    // reading a text file
    #include <iostream>
    #include <fstream>
    #include <string>
    #include <stdlib.h>     /* ADD THIS DEFINE */
    
    
    using namespace std;
    
    
    int main () {
    
    
     string line;
     int i,j,c;
     int Ncoil, Ntank;
     int **Tmin;
     string **Tminstring;
     char str[256];
    
    
     cout << "Number of coils to be cleaned: ";
     cin >> Ncoil;
    
    
     cout << "Number of tanks: ";
     cin >> Ntank;
    
    
    Tmin = new int *[Ncoil];
    
    
     for (int i = 0; i <= Ncoil; ++i)
         {
             Tmin[i] = new int[Ntank];
             for(int j = 0; j <= Ntank; ++j)
                {
                 ifstream myfile ("Tmin.txt");
                    if (myfile.is_open())
                    {
                        while ( myfile.good() )
                            {
                                getline(myfile, line, ' ');
                                char * cstr = new char [line.length()+1];              /* CONVERT C++ STRING TO C CHAR ARRAY */
                                c = atoi(cstr);                                                        /* AND PASS THIS C CHAR ARRAY TO ATOI */
                                Tmin[i][j] = c;
                                myfile.close();
                            }
                    }
                    else cout << "Unable to open output file";
                 }
         }
      return 0;
    }
    The question now is; does it do what you want it to do.
    Last edited by Vespasian; 03-25-2013 at 11:50 AM.

  4. #4
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,447
    Quote Originally Posted by Vespasian
    Below compiles fine:
    "Compiles" and "works correctly" are not necessarily the same thing.
    Elkvis likes this.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  5. #5
    Registered User Vespasian's Avatar
    Join Date
    Aug 2011
    Posts
    181
    Quote Originally Posted by laserlight View Post
    "Compiles" and "works correctly" are not necessarily the same thing.
    Yeah I edited the post just after posting:
    The question now is; does it do what you want it to do.

  6. #6
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,452
    > for (int i = 0; i <= Ncoil; ++i)
    > for(int j = 0; j <= Ntank; ++j)
    Repeat after me - this is a buffer overrun

    If you've got N of something, then you loop from 0 to N-1, which is conveniently written as
    for ( i = 0 ; i < N ; i++ )
    iMalc, Elysia and jimblumberg like this.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  7. #7
    Registered User
    Join Date
    Mar 2013
    Posts
    5
    Thanks all! it was really helpful. I am a noob.

    @laserlight : I have changed my code as follows, but i don't know how do this -->
    Then, use the return value of getline, not good(), to control the inner loop.
    can you explain me in more details.

    New code:
    Code:
    // reading a text file
    #include <iostream>
    #include <fstream>
    #include <string>
    
    using namespace std;
    
    int main () {
    
     string line;
     int i,j,c;
     int Ncoil, Ntank;
     int **Tmin, **Tmax;
     
     char str[256];
    
     cout << "Number of coils to be cleaned: ";
     cin >> Ncoil;
    
     cout << "Number of tanks: ";
     cin >> Ntank;
    
    Tmin = new int *[Ncoil];
    ifstream myfile ("Tmin.txt");
    if (myfile.is_open())
        {
            
                for (int i = 0; i <= Ncoil; ++i)
                  {
                     Tmin[i] = new int[Ntank];
                     for(int j = 0; j <= Ntank; ++j)
                        {
                                 getline(myfile, line, ' ');
                                while (???????)
                                {
                                c = atoi(line.c_str());
                                Tmin[i][j] = c;
                                cout<< Tmin[i][j]<<endl;
                                }
                        }
                        
                 }
                myfile.close();
        }
    
    else cout << "Unable to open Tmin file";
        
          
      
      return 0;
    }
    Last edited by pratras; 03-25-2013 at 02:48 PM.

  8. #8
    Registered User
    Join Date
    Mar 2013
    Posts
    5
    Finally this one is working, thanks all.

    I have one more question. Should I free the memory space and how?
    Code:
    // reading a text file
    #include <iostream>
    #include <fstream>
    #include <string>
    
    using namespace std;
    
    int main () {
    
     string line;
     int i,j,c;
     int Ncoil, Ntank;
     int **Tmin, **Tmax;
     
     char str[256];
    
     cout << "Number of coils to be cleaned: ";
     cin >> Ncoil;
    
     cout << "Number of tanks: ";
     cin >> Ntank;
    
    Tmin = new int *[Ncoil];
    ifstream myfile ("Tmin.txt");
    if (myfile.is_open())
        {
            do{
                for (int i = 0; i < Ncoil; ++i)
                  {
                     Tmin[i] = new int[Ntank];
                     for(int j = 0; j < Ntank; ++j)
                        {
                            myfile >> Tmin[i][j];
                                 /*getline(myfile, line, ' ');
                                c = atoi(line.c_str());
                                Tmin[i][j] = c;
                                cout<< Tmin[i][j]<<endl; */
                            cout << Tmin[i][j]<<' ';
                                }
                        }
                        
                 }while(!myfile.eof());
        myfile.close();
         } 
               
        
    
    else cout << "Unable to open Tmin file";
            
     cin.get();         
      
      return 0;
    }

  9. #9
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,450
    Quote Originally Posted by pratras View Post
    Finally this one is working, thanks all.

    I have one more question. Should I free the memory space and how?
    Use a container, eg std::vector. Then you don't have to free.
    For example (2d array):

    std::vector<std::vector<T>> v(N, std::vector(M));
    <==>
    T v[N][M];

    where N and M are dynamic, ie can be variables.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  10. #10
    Registered User
    Join Date
    Mar 2013
    Posts
    5
    Quote Originally Posted by Elysia View Post
    Use a container, eg std::vector. Then you don't have to free.
    For example (2d array):

    std::vector<std::vector<T>> v(N, std::vector(M));
    <==>
    T v[N][M];

    where N and M are dynamic, ie can be variables.
    can you please elaborate how i can use vector in my case, i didn't get
    "std::vector<std::vector<T>> v(N, std::vector(M));" this line..

  11. #11
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,450
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Read text file, scan and store data into variables?
    By wisdom30 in forum C Programming
    Replies: 8
    Last Post: 04-18-2011, 11:23 PM
  2. Converting integer data from text file
    By tkecanuck341 in forum C++ Programming
    Replies: 2
    Last Post: 03-25-2010, 06:29 AM
  3. read txt file as binary then convert to text
    By 911help in forum C Programming
    Replies: 2
    Last Post: 01-04-2008, 05:29 AM
  4. read text file, convert character numbers to int?
    By hyaku_ in forum C Programming
    Replies: 6
    Last Post: 11-06-2006, 04:04 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21