1

I am a newbie in c++ coding and I found an unusual error in my code. I have no idea where did I go wrong, can anyone point out my mistake ? I am making a code that will create a new line after founding the limit characters inputted by the user. Edit : after declaring j value to zero, I try to cout << b and its equal zero. I am confused now because I have already used getline command to get the number of chars.

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

string input;
string output;
int sum=0;
int counter;
string line;
int w;

int main()
{
    ifstream inFile;
    cout << "Input Text File Name :";
    cin >> input;
    if(inFile.fail())
    {
        cerr << "Error Opening Text" << endl;
        return 1;
    }
    else
        cout << "Output Text File Name :";

    cin >> output;

    ofstream outFile;
    cout << "Texth Width to Format ( >10 ):";
    cin >> w;

    inFile.is_open();
    outFile.open(output);

    while(!inFile.eof())
    {
        getline(inFile,line);
        int b = line.length();
        int i, n, j;
        i = 0;
        n = 1;
        j=0;
        while(j != b)
        {
            for (i; i<n*(w-1); i++)
            {
                outFile << line.at(i);
            }
            i= i;
            outFile << endl;
            n++;
            j += n*(w-1);
        }
        sum=b+sum;
    }
    outFile.close();
    inFile.close();

    cout <<"Number of characters in this Text File is :" << sum;

    return 0;

}

thank you for your help !

  • When you get to `while(j != b)` you haven't yet given `j` a value. And also have a look at [Why is iostream::eof inside a loop condition considered wrong?](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) – Bo Persson Nov 27 '16 at 11:15
  • You should pay close attention to compiler warnings and use a sufficiently high warning level. For example, both GCC and Visual C++ will tell you that something is wrong in your `j += n*(w-1);` line. – Christian Hackl Nov 27 '16 at 11:54
  • I'm curious what the purpose of `i= i;` is. And concur with Christian; jam up your warnings and *fix* the issues addressed. – WhozCraig Nov 27 '16 at 11:57
  • You should also make it easier for people to help you. For example, remove all the `cout` lines and anything else which is not necessary to reproduce the error, and provide contents of a test input file to copy & paste. And you can find out how far your program gets before that "unusual error" actually occurs, and mark the line where it does. – Christian Hackl Nov 27 '16 at 11:59
  • The logic can be simplified quite a bit: `for (std::string line; std::getline(inFile, line); sum += line.length());` – Ray Hamel Nov 27 '16 at 12:07

0 Answers0