atoi(string到int)

atoi

<cstdlib>

int atoi ( const char * str );

 

Convert string to integer

Parses the C string str interpreting its content as an integral number, which is returned as an int value.

The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.

The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.

If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.

Parameters

str
C string beginning with the representation of an integral number.

 

Return Value

On success, the function returns the converted integral number as an int value.
If no valid conversion could be performed, a zero value is returned.
If the correct value is out of the range of representable values, INT_MAX or INT_MIN is returned.

Example

/* atoi example */
#include <stdio.h>
#include <stdlib.h>
int main ()
 {
int i;
char szInput [256];
 printf ("Enter a number: ");
fgets ( szInput, 256, stdin );
 i = atoi (szInput);
printf ("The value entered is %d. The double is %d.\n",i,i*2);
return 0;
}

Output:

Enter a number: 73 The value entered is 73. The double is 146.

那我們應該怎麼用呢?看下面這個例子:
比如我們要從文件中讀取345+234;並且進行計算,沒有空格。
可能我們會想到用內核格式化,在+號,這種方法是可行的,但是如果式子換成345*234,就悲劇了。。
所以我們必須採用逐字符的讀法,然後將數字字符組合成int。
string temp;//temp用來保存數字字符
getline(in_file, infix);
for(int i = 0; i < (int) infix.size(); i++)
{
if(isalnum(infix[j]))//如果是數字字符,需要cctype頭文件
{
temp += infix[j];//追加到temp
}
else
{
cout << atoi(temp) << endl;//遇到其他非數字字符時說明讀取結束,轉換輸出
}
}
當然了,這只是我的一種方法,相信大家有更好的方法。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章