`

Converting Strings To/From Ints:atoi, itoa, sprint

阅读更多

Converting Strings To/From Ints:
atoiitoasprintf and sscanf

Prev: Copying, Finding the Length of 
Strings and the Null Character
 
Next: Copying Strings:
strcpy, strncpy and strcmp



Warning

We are leaving the basic stage for a while to talk about various useful string functions.

If you want, you can skip to abstract data types section and return here later.



Converting a String Into an int Using atoi

Before I leave the string section, I'd like to talk about two useful functions that could come in handy later on. Both of these require the stdlib.h header file.

First of all, atoi. This converts strings, like "23" or even "29dhjds" into integers (returning 23 and 29 respectively in this case).

atoi requires one char * argument and returns an int (not a float!).

If the string is empty, or first character isn't a number or a minus sign, then atoi returns 0.

If atoi encounters a non-number character, it returns the number formed up until that point.

#include <stdio.h>
#include <stdlib.h>

int main() {
  char str1[] = "124z3yu87";
  char str2[] = "-3.4";
  char *str3 = "e24";
  printf("str1: %d\n", atoi(str1));
  printf("str2: %d\n", atoi(str2));
  printf("str3: %d\n", atoi(str3));
  return 0;
}

Output:

str1: 124 
str2: -3 
str3: 0



Converting an int Into a String Using itoa (NOT ANSI C)

Before I continue, I must warn you that itoa is NOT an ANSI function, (it's not a standard C function). You should use sprintf to convert an int into a string, which I'll show you in a moment.

I'll cover itoa in case you've ever wondered what it does.

itoa takes three arguments.

The first one is the integer to be converted.

The second is a char * variable - this is where the string is going to be stored. My program crashed if I pass in a char * variable I've already used, so I passed in a normal sized char array and it worked fine.

The last one is NOT the size of the array, but it's the BASE of your number - base 10 is the one you're most likely to use. Base 2 is binary, 8 is octal and 16 is hexadecimal.

For a small lesson on bases, go back to the Hexadecimal section.

itoa is a very useful function, which is supported by some compilers - shame it isn't support by all, unlike atoi.

Maybe converting a base 10 number into binary format as a string isn't so hard after all...

#include <stdio.h>
#include <stdlib.h>

int main() {
  char str[10]; /* MUST be big enough to hold all 
                   the characters of your number!! */
  
  printf("15 in binary is %s\n",  itoa(15, str, 2));
  printf("15 in octal is %s\n",   itoa(15, str, 8));
  printf("15 in decimal is %s\n", itoa(15, str, 10));
  printf("15 in hex is %s\n",     itoa(15, str, 16));
  return 0;
}

Output:

15 in binary is 1111 
15 in octal is 17 
15 in decimal is 15 
15 in hex is f

... itoa can be useful when you know your program doesn't have to be ANSI C only.



sprintf

You can use this function as an alternative to itoa. It's only half as good as itoa because you can't specify the base of your number to be converted.

sprintf takes three arguments.

The first has to be a char * variable, which means you can use a char array, but make sure it's big enough to hold the converted number.

The second argument is a string containing a format specifier, depending on the format of the number you want to convert.

The third argument is the number you want to convert into a string.

sprintf returns the number of characters in the string (not included the null character).

This example convert a few numbers into string format, and prints out the result:

#include <stdio.h>

int main() {
  char str[10]; /* MUST be big enough to hold all 
                  the characters of your number!! */
  int i;

  i = sprintf(str, "%o", 15);
  printf("15 in octal is %s\n",   str);
  printf("sprintf returns: %d\n\n", i);

  i = sprintf(str, "%d", 15);
  printf("15 in decimal is %s\n", str);
  printf("sprintf returns: %d\n\n", i);

  i = sprintf(str, "%x", 15);
  printf("15 in hex is %s\n",     str);
  printf("sprintf returns: %d\n\n", i);

  i = sprintf(str, "%f", 15.05);
  printf("15.05 as a string is %s\n", str);
  printf("sprintf returns: %d\n\n", i);

  return 0;
}

Output:

15 in octal is 17 
sprintf returns: 2 

15 in decimal is 15 
sprintf returns: 2 

15 in hex is f 
sprintf returns: 1 

15.05 as a string is 15.050000 
sprintf returns: 9



sscanf

For completeness, I'm going to cover sscanf, seeing that it's paired with sprintf.

You could've guessed that it converts a string into various formats.

sscanf takes three arguments, for example:

sscanf(str, "%d", &num);

The first is a char * variable that contains data to be converted.

The second is a string containing a format specifier that determines how the string is converted.

The third is a memory location to place the result of the conversion. Most of the time, you'll need the "address of" operator (&), then a variable name, or you can place a char * variable here.

Now, if the string you pass into sscanf contains a space, only the data up until that space is converted.

sscanf returns the number of items converted.

This example performs conversions in several formats:

#include <stdio.h>

int main() {
  char* ints = "20, 40, 60";
  char* floats = "10.4, 24.66";
  char* hex = "FF, F";

  int i;
  int n;
  float f;
  int h;
  char* s;
  
  i = sscanf(ints, "%d", &n);
  printf("n: %d\n", n);
  printf("sscanff returns: %d\n\n", i);

  i = sscanf(floats, "%f", &f);
  printf("f: %f\n", f);
  printf("sscanff returns: %d\n\n", i);

  i = sscanf(hex, "%x", &h);
  printf("h: %d\n", h);
  printf("sscanff returns: %d\n\n", i);

  i = sscanf(ints, "%s", s);
  printf("s: %s\n", s);
  printf("sscanff returns: %d\n\n", i);

  return 0;
}

Output:

n: 20 
sscanff returns: 1 

f: 10.400000 
sscanff returns: 1 

h: 255 
sscanff returns: 1 

s: 20, 
sscanff returns: 1 

Notice how sscanf ignores the comma when converting to a number (see the result for the string variable, s).



Prev: Copying, Finding the Length of 
Strings and the Null Character
 
Next: Copying Strings:
strcpy, strncpy and strcmp

分享到:
评论

相关推荐

    PWM下载 和SPWM波下载

    // Parameter : Scaler converting 1/N cycles to a GLOBAL_Q freq (Q0) - independently with global Q Uint32 freqScaler_fr; // Parameter : Scaler converting 1/N cycles to a GLOBAL_Q freq (Q0) - ...

    LINUX帮助文档

    * iconv -f fromEncoding -t toEncoding inputFile &gt; outputFile:creates a new file from the given input file by assuming it is encoded in fromEncoding and converting it to toEncoding. 文件搜索命令 * ...

    linux常用命令大全.doc

    * `iconv -f fromEncoding -t toEncoding inputFile &gt; outputFile`:creates a new from the given input file by assuming it is encoded in fromEncoding and converting it to toEncoding. * `find . -maxdepth 1...

    ansi-styles:ANSI转义码,用于在终端中设置字符串样式

    ansi样式 用于在终端中设置字符串样式 ...// NOTE: When converting from truecolor to 256 colors, the original color // may be degraded to fit the new color palette. This means terminals //

    routing:用Go编写的nav-e的路由服务器

    2017/10/22 21:51:08 Converting osm data to graph 2017/10/22 21:51:08 Listening on :8080 原料药 作为后端,该项目提供了一个简单的REST api进行路由 /search/:name :name必须是字符串 GET: ...

    Json.net for .net3.5

    - The JsonSerializer for quickly converting your .NET objects to JSON and back again - Json.NET can optionally produce well formatted, indented JSON for debugging or display - Attributes like ...

    PostgreSQL的Go语言驱动pq.zip

    pq.ParseURL for converting urls to connection strings for sql.Open. Many libpq compatible environment variables Unix socket support Notifications: LISTEN/NOTIFY 示例代码: package main import...

    Erlang and OTP in Action MEAP May 2010

    Chapter Nine: Converting the Cache into a Distributed Application Chapter Ten: Packaging, Services and Deployment Part Three: Working in a Modern Environment Chapter Eleven: Non-native Erlang ...

    PHP and MYSQL Bilbe [英文原版]

    Chapter 8: Strings 137 Chapter 9: Arrays and Array Functions 157 Chapter 10: Numbers 191 Chapter 11: Basic PHP Gotchas 209 Part II: PHP and MySQL 231 Chapter 12: Choosing a Database for PHP 233 ...

    小程序报错: Uncaught TypeError: Converting circular structure to JSON

    今天把最近一直在开发的小程序放安卓手机上测试一下,结果某个页面就一直报错: Uncaught TypeError: Converting circular structure to JSON 先说一下基本的环境: 系统:Android 6.0.1 手机:小米4 微信版本:...

    c++官方网站标准参考资料

    Converting numbers to strings and strings to numbers, How To: Ask Questions The Smart Way ), Forum( 说明:forum部分由于内容太多,体积太大(包括总体积27M,forum部分就占9.5M),而且仅仅是论坛中的讨论而已...

    s7库电子书

    - `S_BIT`: 指针,指向需要转换的数据。 - `N`: 需要转换的整数。 - **输出参数**: - `ENO`: 输出启用标志位。 - `D_INT`: 转换后的双字整数。 ### 实际应用示例 通过具体的例子,如`FC82`的使用场景,读者...

    currency-converter:使用fixer.io API转换货币

    用于的Laravel包装器 ... 该软件包尚不支持fixer.io的高级功能! 如果您正在使用fixer.io premium的功能,则可能甚至不再需要此程序包=&gt;看一下/convert端点。...// Converting currencies Currency::convert(1

    A Methodology For Converting Polygon Based Standard Cell From Bulk CMOS To SOI CMOS

    A Methodology For Converting Polygon Based Standard Cell From Bulk CMOS To SOI CMOS

    SEP - An Algorithm for Converting Covariance to Spherical Error Probable:一种将协方差转换为球面误差概率的算法。-matlab开发

    此函数根据由协方差矩阵的特征值的平方根组成的输入计算球面误差可能半径(等效地,来自坐标系中三变量正态分布的 sigma-x、sigma-y 和 sigma-z,其中存在变量之间没有互相关。)这意味着如果您有一个协方差矩阵并...

    python将字符串转换成数组的方法

    python将字符串转换成数组的方法。分享给大家供大家参考。具体实现方法如下: #----------------------------------------- # Name: string_to_array.py ...# converting it to an array #----------

    将 Char 转换为 Int 的 Java 程序.docx

    // Converting the character to its integer value int a = Character.getNumericValue(ch); // Printing the integer value System.out.println("int value: " + a); }}输出字符值:5整数值:5总结在 Java 中,将...

    A samart way to learn javascript

    27. Converting strings to numbers, numbers to strings(字符串和数字的互相转换):了解不同数据类型之间的转换方法。 28. Controlling the length of decimals(控制小数点长度):通过四舍五入、向下取整等方式...

Global site tag (gtag.js) - Google Analytics