编程论坛's Archiver

kai 发表于 2004-5-7 05:20

[原创]把一串字符串转换为整型

把一串字符串转换为整型

<P>// first method  sscanf ANSI C
#include &lt;stdio.h&gt;
#include &lt;stdlib.h&gt;</P>
<P>int main()
{
   char * buffer = "4711";
   int number;
   int ret;</P>
<P>   ret = sscanf(buffer, "%d", &amp;number);</P>
<P>   if (ret) // success
   {
      printf("%d\n", zahl);
   }</P>
<P>   system("pause");
   return 0;
}</P>
<P>#include &lt;stdio.h&gt;
#include &lt;stdlib.h&gt;
int main()
{
   char * buffer = "4744";
   int i;
   char s[20];
   double d;
   int ret_ok;
   ret_ok = sscanf(buffer, "%d - %s - %g", &amp;i, s, &amp;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 &lt;stdio.h&gt;
#include &lt;stdlib.h&gt;
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 &lt;stdio.h&gt;
#include &lt;stdlib.h&gt;</P>
<P>int main()
{
   char * buffer = "123456";
   const int radix = 10;
   unsigned long number;
    char * error;</P>
<P>    number = strtoul(buffer, &amp;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 &lt;sstream&gt;
#include &lt;iostream&gt;</P>
<P>using namespace std;</P>
<P>int main()
{
    char * buffer = "1234";
    int number;</P>
<P>    stringstream ss(buffer);
    ss&gt;&gt;number;</P>
<P>    if(!ss)
    {
        /*  error */
          exit(1);
    }
    else
          cout&lt;&lt;number;
    return 0;
   
}</P>
<P>// compiled und run in VC 6.0
#include &lt;sstream&gt;
#include &lt;iostream&gt;</P>
<P>using namespace std;</P>
<P>int main()
{
    char * buffer = "123456";
    stringstream ss;
    ss &lt;&lt; buffer;</P>
<P>// now ist ss.str() die number in Stringrepresentation.
cout&lt;&lt;ss.str()&lt;&lt;endl;</P>
<P>// or through the number you get the value
int number;
ss&gt;&gt;number;
cout&lt;&lt;number&lt;&lt;endl;

system("pause");</P>
<P>return 0;
   
}
</P>
[align=right][color=#000066][此贴子已经被作者于2004-05-10 15:22:17编辑过][/color][/align]

C++大粉丝 发表于 2004-5-10 10:27

atol(const char*)

timedcy 发表于 2007-3-19 20:49

atoi()<BR>

蓝一 发表于 2008-6-2 23:13

才发现
KAI的代码真漂亮

mqh21364 发表于 2008-6-3 10:05

[tk02] [tk02]
[tk02] [tk02]
[tk02] [tk02]

页: [1]

Powered by Discuz! Archiver 6.1.0  © 2001-2007 Comsenz Inc.