将一个代表整型数的字符串(比如“-34”)转换为一个整型的数字。 编程指导及提示
发布网友
发布时间:2022-07-28 23:54
我来回答
共1个回答
热心网友
时间:2023-11-17 03:24
// C 语言
#include <stdio.h>
#include <string.h>
int strtoint(char const *s) {
int result = 0;
int len = strlen(s);
for(int i = 0; i < len; ++i) {
if(s[i] >= '0' && s[i] <= '9') {
result = 10 * result + s[i] - '0';
}
}
if(s[0] == '-') return -result;
return result;
}
int main () {
char *s = "-123";
char *t = "456";
int i = strtoint(s);
int j = strtoint(t);
printf("i = %d, j = %d\n", i, j);
}
// C++
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
stringstream stream;
string s("-123"), t("456");
int i, j;
stream.clear();
stream << s;
stream >> i;
cout << i << endl;
stream.clear();
stream << t;
stream >> j;
cout << j << endl;
}