atoi stoi 以及数字与字符串的相互转换(sstream的使用)

https://www.cnblogs.com/weedboy/p/7160152.html

1.c++的atoi和stoi一些区别

对c++标准库中字符串转化为int的两个函数atoi()和stoi()两个有所混乱,特地研究了一下。

stoi()
标准库的函数默认模板
int stoi (const string& str, size_t* idx = 0, int base = 10);
int stoi (const wstring& str, size_t* idx = 0, int base = 10);

标准库中函数的解释 Parses str interpreting its content as an integral number of
the specified base, which is returned as an int value. If idx is not a
null pointer, the function also sets the value of idx to the position
of the first character in str after the number.

意思是解析str的文本转化为为int整数。
idx如果不为空,则会返回一个字符串中遇到的第一个字符(非数字)的字符下标,最后一个base是默认10进制。

example代码:
// stoi example
#include <iostream>   // std::cout
#include <string>     // std::string, std::stoi

int main ()
{
  std::string str_dec = "2001, A Space Odyssey";
  std::string str_hex = "40c3";
  std::string str_bin = "-10010110001";
  std::string str_auto = "0x7f";

  std::string::size_type sz;   // alias of size_t

  int i_dec = std::stoi (str_dec,&sz);
  int i_hex = std::stoi (str_hex,nullptr,16);
  int i_bin = std::stoi (str_bin,nullptr,2);
  int i_auto = std::stoi (str_auto,nullptr,0);

  std::cout << str_dec << ": " << i_dec << " and [" << str_dec.substr(sz) << "]\n";
  std::cout << str_hex << ": " << i_hex << '\n';
  std::cout << str_bin << ": " << i_bin << '\n';
  std::cout << str_auto << ": " << i_auto << '\n';

  return 0;
}
Output

2001, A Space Odyssey: 2001 and [, A Space Odyssey]
40c3:  16579
-10010110001: -1201
0x7f: 127
atoi()
标准库的函数默认模板

int atoi (const char * str);

标准库中函数的解释 Convert string to integer Parses the C-string str
interpreting its content as an integral number, which is returned as a
value of type int. The function first discards as many whitespace
characters (as in isspace) as necessary until the first non-whitespace
character is found. Then, starting from this character, takes an
optional initial plus or minus sign followed by as many base-10 digits
as possible, and interprets them as a numerical value. The string can
contain additional characters after those that form the integral
number, which are ignored and have no effect on the behavior of this
function. If the first sequence of non-whitespace characters in str is
not a valid integral number, or if no such sequence exists because
either str is empty or it contains only whitespace characters, no
conversion is performed and zero is returned.

意思大概是解析字符串返回int。
首先会尽可能丢弃空格,直到找到一个第一个非空格字符,然后从这里开始,采用可选的初始加号和减号尽可能的10个数字来转化。
字符串中包含数字外其他字符会被自动忽略。
只包含空格或者不是有效整数会返回空格。

注意
这个函数是c中传到c++的,不会抛出异常,如果数组超出范围,可能会导致未定义的行为。

总结

stoi用来转哈string的,atoi转化的是char[].
char[]转string可以直接赋值或者用一个循环
string转char
str.data()
str.c_str()
str.copy()
个人感觉stoi的能力还是要比atoi的能力要大一些的,stoi可能往往要比atoi要好用。

https://blog.csdn.net/touzani/article/details/1623850

2.数字转字符串:

用C++的streanstream:

#include <sstream>
#Include <string>
string num2str(double i)
{
        stringstream ss;
        ss<<i;
        return ss.str();
}

注意这几个函数的使用哦

字符串转数字:

int str2num(string s)
 {   
        int num;
        stringstream ss(s);
        ss>>num;
        return num;
}

上面方法很简便, 缺点是处理大量数据转换速度较慢…
C library中的sprintf, sscanf 相对更快

可以用sprintf函数将数字输出到一个字符缓冲区中. 从而进行了转换…
例如:
已知从0点开始的秒数(seconds) ,计算出字符串"H:M:S", 其中H是小时, M=分钟,S=秒

int H, M, S;
string time_str;
H=seconds/3600;
M=(seconds%3600)/60;
S=(seconds%3600)%60;
char ctime[10];
sprintf(ctime, "%d:%d:%d", H, M, S);             // 将整数转换成字符串
time_str=ctime;                                                 // 结果 

与sprintf对应的是sscanf函数, 可以将字符串转换成数字

char    str[] = "15.455";
int     i;
float     fp;
sscanf( str, "%d", &i );         // 将字符串转换成整数   i = 15
sscanf( str, "%f", &fp );      // 将字符串转换成浮点数 fp = 15.455000
//打印
printf( "Integer: = %d ",  i+1 );
printf( "Real: = %f ",  fp+1 ); 
return 0;

输出如下:

Integer: = 16
Real: = 16.455000

3.使用string的一些方法

http://c.biancheng.net/view/1527.html
字符转数字

//This program illustrates the use of sstream objects
#include <sstream>
#include <iostream>
#include <string>
using namespace std;

int main()
{
    string str = "John 20 50"; // string to read from
    const char *cstr = "Amy 30 42"; // Cstring to read from
    istringstream istr1 (str);    // istr1 will read from str
    istringstream istr2; // istr2 will read from cstr
    ostringstream ostr; // The ostringstream object to write to
    string name;
    int score1, score2, average_score;

    // Read name and scores and compute average then write to ostr
    istr1 >> name >> score1 >> score2;
    average_score = (score1 + score2)/2;
    ostr << name << " has average score" << average_score << "\n";
    // Set istr2 to read from the C string and repeat the above
    istr2.str(cstr);
    istr2 >> name >> score1 >> score2;
    average_score = (score1 + score2)/2;
    ostr << name << " has average score" << average_score << "\n";
    // Switch to hexadeximal output on ostr
    ostr << hex;
    // Write Amy's scores in hexadecimal
    ostr << name << "'s scores in hexadecimal are: " << score1 << " and " << score2 << "\n";
    // Extract the string from ostr and print it to the screen
    cout << ostr.str();
    return 0;
}

输出

John has average score35
Amy has average score36
Amy's scores in hexadecimal are: 1e and 2a

请注意,这些类具有 ostream 和 istream 对象的全部功能,包括使用八进制和十六进制等不同进制将数字转换为字符串的能力。当然,它们也是有缺陷的,它们强制程序员创建 sstream 对象,只有这样才能使用它们的插入和提取运算符执行转换。

数字转字符

C++ 11 提供了若干 to_string(T value) 函数来将 T 类型的数字值转换为字符串形式。以下是几个 to_string() 函数的列表:

string to_string(int value)
string to_string(long value)
string to_string(double value)

来看以下代码示例:

int a = 5;
string str = to_string(a*a);
cout << " The square of 5 is " << str << endl;

以上示例即显示了该系列函数的用法。它将打印如下字符串:

The square of 5 is 25

to_string() 函数无法处理非十进制整数的转换。如果需要该功能,则应该使用 ostringsteam 对象来完成该转换。
to_string() 函数无法处理非十进制整数的转换。如果需要该功能,则应该使用 ostringsteam 对象来完成该转换。

字符串到数字的转换可以通过 stoX() 系列函数来执行。该系列函数的成员可以将字符串转换为 int、long、float 和 double 类型的数字。具体语法如下所示:

int stoi(const strings str, size_t* pos = 0, int base = 10)
long stol(const strings str, size_t* pos = 0, int base = 10)
float stof(const strings str, size_t* pos = 0)
double stod(const strings str, size_t* pos = 0)

第一个形参 str 是一个字符串(例如 “-342” 或 “3.48” 等),它将被转换为恰当的数字形式。这些函数可以将 str 可能的最长前缀转换为数字,并返回一个整数地址 pos,pos 中保存了 str 无法被转换的第一个字符的索引。类型 size_t 是在标准库中定义的,常用于表示无符号整数的大小或数组、矢量、字符串中的一个索引。

例如,如果试图转换字符串 “-34iseven”,则将成功返回整数 -34,而无法转换的第一个字符的位置 pos 则被设置为 3。base 形参仅适用于整数转换,指示用于转换的进制。pos 和 base 形参都是可选的,所以它们可以被忽略。如果 pos 被忽略,则不会存储停止字符的索引。如果 base 被忽略,则默认为十进制。如果字符串 str 包含一个无效值,例如 “is-34 even?”,则不会进行转换,函数将抛出一个 invalid_argument 异常。

// This program demonstrates the use of the stoXXX()
// numeric conversion functions.
#include <string>
#include <iostream>
using namespace std;

int main()
{
    string str; // string to convert
    size_t pos; // Hold position of stopping character
    //Convert string to double
    str = "-342.57is a number";
    cout << "The string is " << str << endl;
    double d = stod(str, &pos);
    cout << "The converted double is " << d << endl;
    cout << "The stopping character is " << str[pos] << " at position " << pos << endl;
    // Convert string to int (default to decimal)
    str = "-342.57is a number";
    cout << "\nThe string is " << str << endl;
    int i = stoi(str, &pos);
    cout << "The converted integer is " << i << endl;
    cout << "The stopping character is " << str[pos] <<" at position " << pos << endl;
    // Convert string to int (base is binary)
    str = "01110binary number";
    cout << "\nThe string is " << str << endl;
    i = stoi (str, &pos, 2);
    cout << "The converted binary integer is " << i << endl;
    cout << "The stopping character is " << str[pos] << " at position " << pos << endl;
    return 0;
}

输出

The string is -342.57is a number
The converted double is -342.57
The stopping character is i at position 7

The string is -342.57is a number
The converted integer is -342
The stopping character is . at position 4

The string is 01110binary number
The converted binary integer is 14
The stopping character is b at position 5
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值