例如,123456789将分割成:12345678 和 90000000
#include <iostream>
#include <string>
using namespace std;
int main()
{
int i, d, y;
string str;
getline(cin, str);
d = sizeof(str) / 8;
y = sizeof(str) % 8;
for (i = 0; i < d; i++)
{
cout << str.substr(i * 8, 8) << endl;
}
str = str.substr(8 * d);
cout << str.append(8-y, '0');
return 0;
}
错误提示:
1.
Unhandled exception at 0x77B608F2 in exam.exe: Microsoft C++ exception: std::out_of_range at memory location 0x0133F68C.
2.
Run-Time Check Failure #0 - The value of ESP was not properly saved across a function call. This is usually a result of calling a function declared with one calling convention with a function pointer declared with a different calling convention.
3 个解决方案
#1
sizeof(str)不是字符串长度,str.length()才是
#2
依我看,发明sizeof和发明NULL的人同样该被枪毙!
![求助|C++中substr()函数的参数不能是变量吗? 求助|C++中substr()函数的参数不能是变量吗?](https://image.shishitao.com:8440/aHR0cHM6Ly93d3cuaXRkYWFuLmNvbS9nby9hSFIwY0hNNkx5OW1iM0oxYlM1amMyUnVMbTVsZEM5UWIybHVkRVp2Y25WdEwzVnBMM05qY21sd2RITXZZM05rYmk5UWJIVm5hVzR2TURBeEwyWmhZMlV2TVRZdVoybG0%3D.jpg?w=700&webp=1)
#3
就是这样设计的,sizeof是编译时求值的,不是真正的函数,所以它不可能得到运行时的string长度。
#1
sizeof(str)不是字符串长度,str.length()才是
#2
依我看,发明sizeof和发明NULL的人同样该被枪毙!
![求助|C++中substr()函数的参数不能是变量吗? 求助|C++中substr()函数的参数不能是变量吗?](https://image.shishitao.com:8440/aHR0cHM6Ly93d3cuaXRkYWFuLmNvbS9nby9hSFIwY0hNNkx5OW1iM0oxYlM1amMyUnVMbTVsZEM5UWIybHVkRVp2Y25WdEwzVnBMM05qY21sd2RITXZZM05rYmk5UWJIVm5hVzR2TURBeEwyWmhZMlV2TVRZdVoybG0%3D.jpg?w=700&webp=1)
#3
就是这样设计的,sizeof是编译时求值的,不是真正的函数,所以它不可能得到运行时的string长度。