English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Writing a program needs to convert string to int, so I explored it.
Method 1: atoi function
The atoi function converts a string to an integer, note that you need the stdlib library. So I tried it out:
#include <iostream> #include <string.h> #include <stdlib.h> using namespace std; int main() { string a="11",b="22"; cout<<atoi(a)+atoi(b)<<endl; return 0; }
However, I found an error:
Obviously, atoi needs const char*type, and the type I gave above is string, so we need to add an additional function string.c_str(). string.c_str() is a function in the Borland String class, which returns the address of the first character of the current string.
The return value of the c_str() function is const char*, so we add the c_str() function:
#include <iostream> #include <string.h> #include <stdlib.h> using namespace std; int main() { string a="11",b="22"; cout<<atoi(a.c_str())+atoi(b.c_str())<<endl; return 0; }
Then it was successful, and I hope everyone can point out any inappropriate things.
That's all for this article. I hope the content of this article can bring you some help in learning or work, and I also hope to get more support for the Yelling Tutorial!
Declaration: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume any relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#w.3If you find any infringing content, please report it by email to: notice#w, replacing # with @, and providing relevant evidence. Once verified, this site will immediately delete the suspected infringing content.