Convert string type to int type in C + +

Source: Internet
Author: User

The write program needs to convert the string to int, so I explored it.

  Method One: Atoi function

  The Atoi function converts a string to an integer, noting that the Stdlib library is required. So I tried it on a bit:

  

1#include <iostream>2#include <string.h>3#include <stdlib.h>4 using namespacestd;5 intMain ()6 {7     stringA=" One", b=" A";8Cout<<atoi (a) +atoi (b) <<Endl;9     return 0;Ten  One}

However, the error was found:

  

Obviously, what Atoi needs is a const char* type, and I'm going to add a function string.c_str () to the above string type. String.c_str is a function in the Borland encapsulated string class that returns the first character address of the current string.

The return value of the C_STR function is const char*, so we add the C_str () function:

 

#include <iostream><string.h><stdlib.h>usingnamespace  std; int Main () {    string a="One", b=" ;    cout<<atoi (A.c_str ()) +atoi (B.c_str ()) <<Endl;     return 0 ;}

And then succeed, what's wrong with the hope that you will point out.

  

  

Convert string type to int type in C + +

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.