0

I would like to write a program that read characters from a file and display them with two spaces between each character.

However, I am limited to 10 characters per line.

How could I make the program return to a new line every 10 characters?

// OUTPUT CHARACTERS FROM FILE

cout << "Characters read from file are: " << endl;

inFile.get(textWritten);
while (inFile) {
    if (textWritten == SPACE) cout << "    ";
    cout << textWritten << "  ";
    inFile.get(textWritten);
}
tadman
  • 208,517
  • 23
  • 234
  • 262
alexductm
  • 3
  • 1
  • by my count that's 3 (10 / 1 char + 2 spaces) characters a line.... So why not just `cout << "\n"` every 3 chars? – UKMonkey Mar 19 '18 at 16:17
  • @Gourav Manna All you need is to learn to count up to 10.:) – Vlad from Moscow Mar 19 '18 at 16:17
  • Off Topic: `inFile.get(textWritten); while (inFile)` should just be `while (inFile.get(textWritten))`. For more on why see: https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong – NathanOliver Mar 19 '18 at 16:19
  • You may want to use `std::getline(inFile, textWritten);` instead of `inFile.get` – Thomas Matthews Mar 19 '18 at 16:28

2 Answers2

0

You can do something like this:

int charCount = 0;
//inside the while-Loop
if(charCount == 10) {
    cout << "\n";
    charCount = 0;
}
//if it is a new character
charCount++;
0

Try this:

#include <iostream>
#include <fstream>
using namespace std;

int main() {
  ifstream file("something.txt"); // Open textfile

  for (char c, i = 1; file >> c; i += 3) {
    cout << c;          // Print the character
    if (i > 9) {
        cout << endl;   // Print newline
        i = 0;          // Reset I
    } else {
        cout << "  ";   // Only print space if it's not the last character
    }
  }

  return 0;
}

BTW: i is actually a char, but you can use it like an int.

kwyntes
  • 1,045
  • 10
  • 27