CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 7 of 7
  1. #1
    Join Date
    Jan 2010
    Location
    Netherlands
    Posts
    12

    Question Getline_input_to_int

    Hello,

    Is it possible to convert the input you get from using the getline(inputfile, string) to an int?

    Say i have a file "abcd.txt", with the following content:

    6
    3

    How can i convert the 6 and 3, which are strings because of the getline() function, to an integer?

    Thank you very much,

    Neil.

  2. #2
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Seattle, WA
    Posts
    10,895

    Re: Getline_input_to_int

    There are many ways to convert a string to an int. Some may be better than others for various situations:

    sscanf()
    istringstream
    strtol()
    atoi()
    boost::lexical_cast

    to name just a few.

  3. #3
    Join Date
    Jan 2010
    Location
    Netherlands
    Posts
    12

    Re: Getline_input_to_int

    Thanks for your quick reply, i get an error whilst compiling though.

    Heres my code:
    <code>

    #include <iostream>
    #include <fstream>
    #include <string>
    #include <cstdlib>
    using namespace std;

    int main()
    {
    ifstream diagram;
    diagram.open("diagram.in");
    string line;
    int one;
    int two;
    getline(diagram, line);
    one = atoi(line);
    getline(diagram, line);
    two = atoi(line);
    system("PAUSE");
    return 0;
    }

    </code>

    The error i get is the following: error C2664: 'atoi' : cannot convert parameter 1 from 'std::string' to 'const char *'



    - Neil.

  4. #4
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Seattle, WA
    Posts
    10,895

    Re: Getline_input_to_int

    Yes, atoi() is a C function, so it doesn't know about std::string. The error is telling you exactly what's wrong. You'll need to use std::string's compatibility method, c_str().

  5. #5
    Join Date
    Aug 2000
    Location
    West Virginia
    Posts
    7,721

    Re: Getline_input_to_int

    Are there other chars on each line besides what you have shown ?
    if not, whu not read directly into an int variable ?

  6. #6
    Join Date
    Jan 2010
    Location
    Netherlands
    Posts
    12

    Re: Getline_input_to_int

    Thank you, Lindley. That helped!

    @ Philip, is there a way i can read it directly into int?

    - Neil.

  7. #7
    Join Date
    Aug 2000
    Location
    West Virginia
    Posts
    7,721

    Re: Getline_input_to_int

    Code:
    int one , two;
    
    diagram >> one >> two;

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured