Ken*_*Lin 3 c++ arrays string substring
例如:
读取文件输入并存储到
char fileInput[200];
Run Code Online (Sandbox Code Playgroud)
然后我用它将它转换成某种字符串数组
string fileStrArr(fileInput);
Run Code Online (Sandbox Code Playgroud)
该文件的测试输出如下所示:50014002600325041805如何使用带循环的子字符串来获取每个4位数的字符并将其转换为诸如"5001""4002""6003"...之类的数字?所以我想我需要先将字符串数组变成字符串?
将字符数组转换为std :: string类型的对象非常简单
std::string s( fileInput );
Run Code Online (Sandbox Code Playgroud)
只要fileInput为零终止.否则你必须使用其他一些std :: string构造函数
如果我理解正确你需要以下内容
#include <iostream>
#include <string>
#include <vector>
int main()
{
const size_t N = 4;
std::string s( "50014002600325041805" );
std::vector <int> v;
for ( size_t i = 0; i != s.size(); )
{
std::string t = s.substr( i, N );
v.push_back( std::stoi( t ) );
i += t.size();
}
for ( int x : v ) std::cout << x << ' ';
std::cout << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
程序输出是
5001 4002 6003 2504 1805
Run Code Online (Sandbox Code Playgroud)