【发布时间】:2017-08-11 05:00:28
【问题描述】:
我正在尝试编写一个程序,该程序从文件中获取输入行并使其正好为 80 个字符(假设输入行始终小于 80),然后打印该行。这是通过在以下标点符号后添加最多两个空格来完成的:.,!;?如果一行少于 41 个字符,则直接打印。
如果该行仍然不是 80 个字符,则可以在整个行中添加随机空格,均匀性对此无关紧要。
输入文件是: Lorem Ipsum 只是印刷和排版行业的虚拟文本吗?洛雷姆 自 1500 年代以来,Ipsum 一直是业界标准的虚拟文本,当时 不知名的打印机拿了一个打字机,并把它打乱成一个打字标本 书。它不仅经历了五个世纪,而且经历了电子领域的飞跃 排版,基本保持不变。 1960年代普及 随着包含 Lorem Ipsum 段落等的 Letraset 表的发布 最近使用了 Aldus PageMaker 等桌面排版软件,包括 Lorem Ipsum 的版本。
输出文件应如下所示:
这个。注意每一行是如何对齐的
这是我的代码:
const int maxLine = 80;
ifstream fin("unjustified.txt");
ofstream fout("justified.txt");
void randomSpace(string &input);
void spaceAdder(string &input);
int main() {
string inputLine;
while (getline(fin, inputLine)) {
if (inputLine.size() > 40)
{
spaceAdder(inputLine);
}
else {
fout << inputLine << endl;
}
}
system("pause");
fin.close();
fout.close();
return 0;
}
void spaceAdder(string &input) {
int perPos = input.find('.');
while (perPos != string::npos && input.size() < maxLine) {
input.insert(perPos + 1, " ");
perPos = input.find('.', perPos + 1);
}
int commaPos = input.find(',');
while (commaPos != string::npos && input.size() < maxLine) {
input.insert(commaPos + 1, " ");
commaPos = input.find(',', commaPos + 1);
}
int questPos = input.find('?');
while (questPos != string::npos && input.size() < maxLine) {
input.insert(questPos + 1, " ");
questPos = input.find('?', questPos + 1);
}
int semiPos = input.find(';');
while (semiPos != string::npos && input.size() < maxLine) {
input.insert(semiPos + 1, " ");
semiPos = input.find(';', semiPos + 1);
}
int exclamPos = input.find('!');
while (exclamPos != string::npos && input.size() < maxLine) {
input.insert(exclamPos + 1, " ");
exclamPos = input.find('!', exclamPos + 1);
}
if (input.size() < maxLine) {
randomSpace(input);
}
else
fout << input << endl;
}
void randomSpace(string &input) {
srand(time(0));
while (input.size() < maxLine) {
int spacePos = input.find(" ");
bool i = (rand() % 2 == 1) ? true : false;
if (i = true && spacePos != string::npos)
{
input.insert(spacePos, " ");
spacePos = input.find(" ", spacePos + 1);
}
}
fout << input << endl;
}
但是我的代码创建的输出是:
这个。请注意第 2 行和第 4 行如何与文本的其余部分不对齐
我终其一生都无法弄清楚我的代码出了什么问题。请指出我正确的方向!谢谢
【问题讨论】:
-
srand(time(0));应该在程序开始时调用一次,否则每次在同一秒内调用该函数时,您只会一遍又一遍地获得相同的序列。跨度> -
请将您的输出发布为文本,而不是图像。
-
提示1:不是这两行太长。其他行太短了。
-
提示 2。
if (i = true && ...并没有像你想象的那样做。 -
谢谢。我非常感谢你的提示。让我在提示 2 中解释我的想法,请告诉我我的逻辑哪里错了;我是一个新程序员。所以选择0-1之间的随机数,如果选择了1,且空格的位置不在行尾,则加一个空格。