每10个字符返回一个新行

时间:2018-03-19 16:15:47

标签: c++ io return

我想编写一个程序来读取文件中的字符,并在每个字符之间显示两个空格。

但是,每行限制为10个字符。

如何让程序每10个字符返回一个新行?

// 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);
}

2 个答案:

答案 0 :(得分:0)

您可以这样做:

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

答案 1 :(得分:0)

试试这个:

#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实际上是char,但您可以像int一样使用它。