如何使用string.substr()函数? [英] How to use string.substr() function?

查看:82
本文介绍了如何使用string.substr()函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想制作一个程序,该程序将读取字符串格式的某个数字并像这样输出:如果数字为12345,则应输出12 23 34 45。我尝试使用c ++字符串库中的substr()函数,但它给了我奇怪的结果-它输出1 23 345 45而不是预期的结果。为什么?

I want to make a program that will read some number in string format and output it like this: if the number is 12345 it should then output 12 23 34 45 . I tried using the substr() function from the c++ string library, but it gives me strange results - it outputs 1 23 345 45 instead of the expected result. Why ?

#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
int main(void)
{
    string a;
    cin >> a;
    string b;
    int c;

    for(int i=0;i<a.size()-1;++i)
    {
        b = a.substr(i,i+1);
        c = atoi(b.c_str());
        cout << c << " ";
    }
    cout << endl;
    return 0;
}


推荐答案

如果我是正确的, substr()的第二个参数应该是子字符串的长度。

If I am correct, the second parameter of substr() should be the length of the substring. How about

b = a.substr(i,2);

这篇关于如何使用string.substr()函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆