c++小问题求解答!!!

时间:2022-06-08 17:34:51
按要求分解字符串,输入两个数M,N;M代表输入的M串字符串,N代表输出的每串字符串的位数,不够补0。例如:输入2,8, “abc” ,“123456789”,则输出为“abc00000”,“12345678“,”90000000”。

我的代码如下:

#include<iostream>
#include<string>
using namespace std;
int main ()
{
int m,n; //定义两个数,m代表字符串数量,n代表限制长度
int count = 0; //表示第几个字符串
cin>>m>>n; //键盘输入两个数
const int num = m + 1; //舍弃第0个字符串,方便计算
string str[num]; //创建字符串数组

for(int i = 1;i <= m;i++) //循环输入m个字符串
{
cin>>str[i];
}

while(m--) //m个字符串进行循环判定
{
count += 1; //舍弃第0个字符串,从第一个判定
int len = strlen(str[count]); //计算字符串长度

if(len <= n) //长度小于等于n的,末尾添加‘0’,直到长度等于n
{
while(len < n)
{
str[count] += '0';
len++;
}
cout<<str[count]<<endl; //输出
}
else
{
int i = 0; //创建两个数
int j = 1;
while(true)
{
if(len < n) //设定循环跳出条件
{
break;
}

string s = str[count].substr(i * n,j * n); //取出第到底i * n到j * n个字符
cout<<s<<endl; //输出
len -= n; //长度减去n
i++; //基数加一
j++;
}
while(len < j * n) //为字符串加‘0’,直到长度等于j * n
{
str[count] += '0'
len++;
}
string s = str[count].substr(i * n,j * n); //取出最后一组
cout<<s<<endl; //输出
}

}
return 0;

}

3 个解决方案

#1


这种操作还是用传统的char *比较方便

#2


那我这么写不行的吗?

#3


搞出来了。。
#include<iostream>
#include<string>
#include<vector> 
using namespace std;
int main ()
{
int m,n; //定义两个数,m代表字符串数量,n代表限制长度
int count = 0; //表示第几个字符串
cin>>m>>n; //键盘输入两个数
const int num = m + 1; //舍弃第0个字符串,方便计算
vector<string> str(num); //声明变长数组

for(int i = 1;i <= m;i++) //循环输入m个字符串
{
cin>>str[i];
}
cout<<endl;

for(int i = 1;m > 0;i++) //m个字符串进行循环判定
{
int len = str[i].length(); //计算字符串长度

if(len <= n) //长度小于等于n的,末尾添加‘0’,直到长度等于n
{
while(len < n)
{
str[i] += "0";
len++;
}
cout<<str[i]<<endl; //输出
}
else
{
int x = 0; //创建两个数
int y = 1;
while(true)
{
if(len < n) //设定循环跳出条件
{
break;
}

string s = str[i].substr(x * n,y * n); //取出第到底i * n到j * n个字符
cout<<s<<endl; //输出
len -= n; //长度减去n
x++; //基数加一
y++;
}
len = str[i].length();
while(len < y * n) //为字符串加‘0’,直到长度等于j * n
{
str[i] += "0";
len++;
}
string s = str[i].substr(x * n,y * n); //取出最后一组
cout<<s<<endl; //输出
}
m--; //字符串数减1
}
return 0;

}

#1


这种操作还是用传统的char *比较方便

#2


那我这么写不行的吗?

#3


搞出来了。。
#include<iostream>
#include<string>
#include<vector> 
using namespace std;
int main ()
{
int m,n; //定义两个数,m代表字符串数量,n代表限制长度
int count = 0; //表示第几个字符串
cin>>m>>n; //键盘输入两个数
const int num = m + 1; //舍弃第0个字符串,方便计算
vector<string> str(num); //声明变长数组

for(int i = 1;i <= m;i++) //循环输入m个字符串
{
cin>>str[i];
}
cout<<endl;

for(int i = 1;m > 0;i++) //m个字符串进行循环判定
{
int len = str[i].length(); //计算字符串长度

if(len <= n) //长度小于等于n的,末尾添加‘0’,直到长度等于n
{
while(len < n)
{
str[i] += "0";
len++;
}
cout<<str[i]<<endl; //输出
}
else
{
int x = 0; //创建两个数
int y = 1;
while(true)
{
if(len < n) //设定循环跳出条件
{
break;
}

string s = str[i].substr(x * n,y * n); //取出第到底i * n到j * n个字符
cout<<s<<endl; //输出
len -= n; //长度减去n
x++; //基数加一
y++;
}
len = str[i].length();
while(len < y * n) //为字符串加‘0’,直到长度等于j * n
{
str[i] += "0";
len++;
}
string s = str[i].substr(x * n,y * n); //取出最后一组
cout<<s<<endl; //输出
}
m--; //字符串数减1
}
return 0;

}