[英]converting a string (containing numbers) into an integer and returning that integer
我現在正在使用C ++編寫代碼,在該代碼中我應該做一個接收數字字符串並將其轉換為整數然后返回該值的函數。 例如,如果我將“ 4569”作為字符串傳遞,它將返回4569整數值。 誰能幫我指出我錯了嗎? 提前致謝 :)
#include<iostream>
#include<cstdlib>
using namespace std;
void getInput(char arr[] , int size )
{
cout<<"ENTER THE ARRAY"<<endl;
cin.getline(arr,size);
}
int stringToInteger(char source[])
{
int sum = 0;
int y=strlen(source);
int multiply = 1;
for( int i=y ; i>=0 ; i--)
{
int n= source[i];
sum = (sum + (n * multiply));
multiply = (multiply *10);
}
return sum;
}
int main()
{
const int size =100;
char inputArr [size];
getInput (inputArr, size );
int x = stringToInteger (inputArr );
cout<<"THE RETURNED INTEGER VALUE IS"<<endl;
cout<<x<<endl;
return 0;
}
首先,您從字符串末尾的字符開始。 如果長度(由strlen
返回)為y
,則有效索引為0 <= i < y
。 因此,您的循環要從y-1
開始。
for( int i=y-1 ; i>=0 ; i--)
^^
然后,您需要通過減去ASCII值'0',將每個ASCII數字轉換為0到9之間的值:
int n= source[i] - '0';
^^^^^
然后,您可能應該檢測並處理錯誤的輸入,包括太大而無法用int
表示的值。
然后,一旦您了解了如何在C中實現此功能,請將其丟棄並使用C ++庫:
std::string input;
std::getline(std::cin, input);
int x = std::stoi(input);
嘗試,
#include <stdlib.h>
並在您的main()
:
int x = atoi(inputArr);
我不確定為什么不使用atoi
或std::stoi
,但是您的算法存在邏輯缺陷:
int stringToInteger(char source[])
{
int sum = 0;
int y=strlen(source);
int multiply = 1;
for(int i=y - 1; i >= 0; i--) // you were starting at y, which is 1 passed the end of the array
{
int n = (int)(source[i] - '0');
sum += (n * multiply); // += makes this more readable
multiply *= 10; // same with *=
}
return sum;
}
就是說,如果這不是家庭作業,您應該使用https://stackoverflow.com/a/18238566/529761或https://stackoverflow.com/a/18238682/529761發布的解決方案(具體取決於您的語言要求)。
同樣,即使此更改也有1個潛在的問題:如果source
包含非數字字符,它將無法正常工作。 一種簡單的處理方法是,如果遇到不應該出現的字符,請進行檢查:
int stringToInteger(char source[])
{
int sum = 0;
int y=strlen(source);
int multiply = 1;
for(int i=y - 1; i >= 0; i--) // you were starting at y, which is 1 passed the end of the array
{
int n = (int)(source[i] - '0');
if (n < 0 || n > 9)
break;
sum += (n * multiply); // += makes this more readable
multiply *= 10; // same with *=
}
return sum;
}
無需調用strlen
-在允許使用庫函數(上述atoi
和strtol
)之前,可以使用以下代碼:
int stringToInteger(char *source)
{
int sum = 0;
if (source)
while (*source >= '0' && *source <= '9')
{
sum = 10*sum + *source - '0';
source++;
}
return sum;
}
正如每個其他答案所暗示的那樣,您忘記了ASCII字符'0'和二進制值0
之間的區別。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.