Solved

converting string to int

Posted on 2004-10-16
3
210 Views
Last Modified: 2010-04-24
hi,
i'm using visual studio. i consider myself a novice when it comes to c++

i have a string that i'd like to convert to an int:

//not real code...
int functionReturningInt(){
    char number[8];
    //read user input from std in
    cin.getline (number, sizeof(number));
    //do something to number so it becomes an int
    return number;
}

i can just do cin >> number (or << whatever, it's late), but i'd like to have some kind of user validation.
any ideas?
btw, take the code sample as pseudocode :)
thanks,
daniel416
0
Comment
Question by:daniel416
3 Comments
 
LVL 48

Accepted Solution

by:
AlexFM earned 400 total points
ID: 12331354
int functionReturningInt(){
    char number[8];
    //read user input from std in
    cin.getline (number, sizeof(number));

    int n = atoi(number);

    return n;
}
0
 
LVL 16

Assisted Solution

by:nonubik
nonubik earned 100 total points
ID: 12332974
You can also use sscanf(..) function:

int functionReturningInt(){
    char number[8];
    //read user input from std in
    cin.getline (number, sizeof(number));
    int n;
    if(sscanf(number, "%d", &n) != 1)
    {
       //could not convert string to number
       cout << "Error converting";
       return 0;
    }
    return n;
}
0
 
LVL 3

Author Comment

by:daniel416
ID: 12336313
Thanks!
I used the atoi solution, but the sscanf looks interesting, too (maybe i'll come in useful one day)
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

The following diagram presents a diamond class hierarchy: As depicted, diamond inheritance denotes when two classes (e.g., CDerived1 and CDerived2), separately extending a common base class (e.g., CBase), are sub classed simultaneously by a fourt…
In Easy String Encryption Using CryptoAPI in C++ (http://www.experts-exchange.com/viewArticle.jsp?aid=1193) I described how to encrypt text and recommended that the encrypted text be stored as a series of hexadecimal digits -- because cyphertext may…
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…
This tutorial demonstrates a quick way of adding group price to multiple Magento products.

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now