gpt4 book ai didi

c++ - 如何使用 string.substr() 函数?

转载 作者:IT老高 更新时间:2023-10-28 12:32:44 29 4
gpt4 key购买 nike

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

#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() 的第二个参数应该是子串的长度。怎么样

b = a.substr(i,2);

?

关于c++ - 如何使用 string.substr() 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2477850/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com