[原创]把一串字符串转换为整型
把一串字符串转换为整型<P>// first method sscanf ANSI C
#include <stdio.h>
#include <stdlib.h></P>
<P>int main()
{
char * buffer = "4711";
int number;
int ret;</P>
<P> ret = sscanf(buffer, "%d", &number);</P>
<P> if (ret) // success
{
printf("%d\n", zahl);
}</P>
<P> system("pause");
return 0;
}</P>
<P>#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);</P>
<P> if(ret_ok)
printf("%d\n", i);</P>
<P> system("pause");
return 0;</P>
<P>}</P>
<P>// second method atoi (ANSI C)
#include <stdio.h>
#include <stdlib.h>
int main()
{
char* buffer = "1234";
int number;</P>
<P> number = atoi(buffer);</P>
<P> printf("%d\n", number);</P>
<P> system("pause");
return 0;
}
//3. Method - strtoul (ANSI C)
#include <stdio.h>
#include <stdlib.h></P>
<P>int main()
{
char * buffer = "123456";
const int radix = 10;
unsigned long number;
char * error;</P>
<P> number = strtoul(buffer, &error, radix);</P>
<P> 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</P>
<P>#include <sstream>
#include <iostream></P>
<P>using namespace std;</P>
<P>int main()
{
char * buffer = "1234";
int number;</P>
<P> stringstream ss(buffer);
ss>>number;</P>
<P> if(!ss)
{
/* error */
exit(1);
}
else
cout<<number;
return 0;
}</P>
<P>// compiled und run in VC 6.0
#include <sstream>
#include <iostream></P>
<P>using namespace std;</P>
<P>int main()
{
char * buffer = "123456";
stringstream ss;
ss << buffer;</P>
<P>// now ist ss.str() die number in Stringrepresentation.
cout<<ss.str()<<endl;</P>
<P>// or through the number you get the value
int number;
ss>>number;
cout<<number<<endl;
system("pause");</P>
<P>return 0;
}
</P>
[align=right][color=#000066][此贴子已经被作者于2004-05-10 15:22:17编辑过][/color][/align]
atol(const char*) atoi()<BR> 才发现
KAI的代码真漂亮 [tk02] [tk02]
[tk02] [tk02]
[tk02] [tk02]
页:
[1]
