소프트웨어융합/경희대 c++ 과제

[c++]4. 최대 길이를 정한 텍스트파일

류지나 2020. 7. 15. 00:20

5. 아래와 같은 텍스트파일을 읽고 각 라인의 최대 길이를 입력 받은 후 새로운 텍스트
파일을 만드는 프로그램을 작성하라.

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
	char ch;
	int length;
	cout << "length = ";
	cin >> length;
	ifstream ifs;
	ofstream ofs;
	ifs.open("input.txt");
	ofs.open("output.txt");
	int cur = 0;
	while (ifs.get(ch))
	{
		if (ch != '\n')
		{
			ofs.put(ch);
			cur++;
			if (cur % length == 0)
			{
				ofs.put('\n');
				cur = 0;
			}
		}
	}
	ifs.close();
	ofs.close();
	return 0;
}
#include <iostream>
#include <string>
#include <fstream>
using namespace std;

int main() {
	int len;
	string line;
	cout << "length = ";
	cin >> len;
	ifstream s1("input.txt");
	ofstream fout("fin.txt");

	int i = 0, now_len = 0;
	while (getline(s1, line)) {
		int ho = line.length();
		while (1) {
			if (i == ho) {
				i = 0;
				break;
			}
			if ((now_len == 0) and (line.at(i) == ' ')) {
				i++;
				continue;
			}
			else {
				fout << line.at(i);
				i++;
				if (now_len == len-1) {
					now_len = 0;
					fout << endl;
				}
				else {
					now_len++;
				}
			}

		}
	}
	s1.close();
	fout.close();
	return 0;
}