'C++ limit line size to N characters in .txt file
Would be so happy if somebody helped me with this task: I have a .txt file, the program should ask a user for a number N (10<=n<=100) amount of characters per line. That means that every line in the .txt file can have not more than N characters, but words and symbols should be logically split. Example:
Hello World, It’s (me) again!
-> n=7 ->
Hello
World,
It’s
(me)
again!
So where am I now:
#include <fstream>
#include <iostream>
using namespace std;
int main() {
int ok; // ability to continue
do
{
int n;
cout<< "Enter n:"<<endl; //ask a number from user
cin>> n;
while(n<10 || n>100) //set a number limit
{ //if n not in the limit
cout<< "Enter n:"<<endl; //ask again
cin>> n;
}
fstream f; //local file name in program
char c; //will read file by symbol
f.open("text.txt", ios::in); //open file
while (f) {
for (int i = 1; f >> c; i ++) { //here should be the conditions to add line break
cout << c; //after N characters
if (i > n) { //but should not wrap words
cout << "\n";
i = 0; //here it starts counting from 0 after \n
}}
};
f.close();
cout << "\n\n Continue (1) End (0)?" << endl;
cin >> ok;
cin.ignore();
}
while (ok==1);
}
As I understand the logic, it should count the file by character, and if character index==7, it should cout ‘\n’. But I have problems with implementing this idea in code.
All this code does - removes all spaces and wraps words.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
