思路1:
先对不为8的倍数的字符串结尾补0,使其刚好为8的倍数。然后每隔8个字符输出并打印换行符。
代码:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str;
while (cin >> str)
{
// 补0
int len = str.size();
if (len % 8 != 0)
{
int count = 8 - len % 8;
str.append(count, '0');
}
// 按格式输出
int newLen = str.size();
for (int i = 0; i < newLen; i += 8)
{
cout << str.substr(i, 8) << endl;
}
}
return 0;
}思路2:
使用输入输出标准库自带的功能。使用cout对象的成员函数width()指定输出域宽,使用成员函数fill()指定填充字符,使用流操纵符left指定左对齐。注意,即使str剩余的字符串长度不足8,str.substr(0, 8)也能正常获取剩余的字符,不会报错。
代码:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str;
while (cin >> str)
{
int len = str.size();
for (int i = 0; i < len; i += 8)
{
cout.width(8);
cout.fill('0');
cout << left << str.substr(i, 8) << endl;
}
}
return 0;
}
京公网安备 11010502036488号