MiT_73
@MiT_73

Как записать стихотворный текст “лесенкой” (по одному слову в строке)?

Задание:
Стихотворный текст (в строке не более 80 символов) имеет четырех строчные строку. Записать его “лесенкой” (по одному слову в строке), вставляя пустую строку после каждого четверостишия.
Мой код:
#include "stdafx.h"
#include <iostream>
#include <string>
#include "conio.h"

using namespace std;

size_t LengthOfUtf8String(const std::string &utf8_string) {
	return distance(utf8_string.begin(), utf8_string.end());
}

int main(int argc, const char* argv[])
{
	char sub;
	int i = 0, n = 0;
	string a[80];
	string s;

	system("CLS");
	cout << "Input str" << endl;
	cin >> s;

	do {
		i += 1;
		if ((s[i] == ' ') || (s[i] == ',')) {
			n += 1;
			a[n] = sub;
			sub = ' ';
		}
		else sub = sub + s[i];
	} while (!(i == LengthOfUtf8String(s)));
	n += 1;
	a[n] = sub;
	cout << endl;


	for (i = 1; i <= n; i++)
	{
		if (i % 4 == 1)  cout << a[i] << endl;
		if (i % 4 == 2)  cout << ' ' << a[i] << endl;
		if (i % 4 == 3)  cout << "   " << a[i] << endl;
		if (i % 4 == 0) {
			cout << "    " << a[i] << endl;
			cout << endl;

		}
	}
	system("pause");
}


Вопрос: что я сделал не так? И как это нужно сделать правильно?
  • Вопрос задан
  • 927 просмотров
Решения вопроса 1
MiT_73
@MiT_73 Автор вопроса
Upd:
#include "stdafx.h"
#include <iostream>
#include <string>
#include <sstream>

using namespace std;

string toLadder(const string &str) {
	stringstream input(str);
	stringstream output;

	string word;
	for (int counter = 0; input >> word; ++counter) {
		int pad = counter % 4;

		output << string(pad, ' ') << word << "\n";

		if (pad == 3) {
			output << "\n";
		}
	}

	return output.str();
}

int main() {
	cout << "Enter text: ";
	string line;
	getline(std::cin, line);

	cout << endl << toLadder(line);
	system("pause");
}
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы