// first method sscanf ANSI C #include <stdio.h> #include <stdlib.h>
int main() { char * buffer = "4711"; int number; int ret;
ret = sscanf(buffer, "%d", &number);
if (ret) // success { printf("%d\n", zahl); }
system("pause"); return 0; }
#include <stdio.h> #include <stdlib.h> int main() { char * buffer = "4744"; int i; char s[20]; double d; int ret_ok; ret_ok = sscanf(buffer, "%d - %s - %g", &i, s, &d);
if(ret_ok) printf("%d\n", i);
system("pause"); return 0;
}
// second method atoi (ANSI C) #include <stdio.h> #include <stdlib.h> int main() { char* buffer = "1234"; int number;
number = atoi(buffer);
printf("%d\n", number);
system("pause"); return 0; } //3. Method - strtoul (ANSI C) #include <stdio.h> #include <stdlib.h>
int main() { char * buffer = "123456"; const int radix = 10; unsigned long number; char * error;
number = strtoul(buffer, &error, radix);
if (!*error) { /* no error */ printf("%d\n", number); } system("pause"); return 0; } 4. Method - stringstream (ANSI C++) // compiled und run in VC 6.0, // BC don't support sstream.h
#include <sstream> #include <iostream>
using namespace std;
int main() { char * buffer = "1234"; int number;
stringstream ss(buffer); ss>>number;
if(!ss) { /* error */ exit(1); } else cout<<number; return 0; }
// compiled und run in VC 6.0 #include <sstream> #include <iostream>
using namespace std;
int main() { char * buffer = "123456"; stringstream ss; ss << buffer;
// now ist ss.str() die number in Stringrepresentation. cout<<ss.str()<<endl;
// or through the number you get the value int number; ss>>number; cout<<number<<endl; system("pause");
return 0; }
[此贴子已经被作者于2004-05-10 15:22:17编辑过]