Text file parsing C++

135 views Asked by At

I have been trying to parse through a text file in c++ to read the numbers that are contained within the file. The number of integers on each line and the number of lines is not know. When all the integers are read they will save that integer followed by a ',' and the running total of that line. This will then be outputted to a file chosen by the user. The code I have written is as follows:

#include <iostream>
#include <string>
#include <fstream>

using namespace std;

int main()
{
int i=0,b = 0,num = 100;
int *s1;
string myfilename, mystring, filename;

cout << "Enter the name of the file to open:" << endl;
cin >> myfilename;
cout << "Enter the name of the output file" << endl;
cin >> filename;

ifstream inFile;
ofstream outFile("C:\\Users\\Aidan Howie\\Documents\\University\\Second Year\\C++\\" + filename + ".txt");

inFile.open("C:\\Users\\Aidan Howie\\Documents\\University\\Second Year\\C++\\" + myfilename + ".txt");
if (!inFile)
{
    cout << "Cannot open file" << endl;
    return -1;
}
while (!inFile.eof())
{
    s1 = new int[num];
    for (i = 0; i < s1; i++)
    {
        cout << i << "," << (i + b) / s1;
        b = i+b;
        cout << endl;
    }

}

inFile.close();
system("PAUSE");

}

However receive the error:

error C2446: '<' : no conversion from 'int *' to 'int'  

Can anyone explain how to fix this and whether there is an easier way for me to read the unknown integers on the file

2

There are 2 answers

3
David On

s1 is a pointer to an int, while i is an int. So essentially what you're doing is checking if 6 < 0x55ddab.

The right way to do it is: i < *s1

Also, don't forget to delete s1 before your while loop repeats.

Also, I'm just going to put a note that what you're doing makes no sense, nonetheless, using i < *s1 will fix your error.

6
Carey Gregory On

s1 is an array of ints, which means that when you use the name s1 without an index, it is a pointer. Therefore, your comparison of i < s1 is asking if i is less than the address of s1, and that's not a valid comparison. Your line of code should look like this:

for (i = 0; i < num; i++)

Also, inFile.eof() isn't doing what you think it is. The only way you're going to get an EOF on inFile is if the user types ctrl+D. You should have the user enter some sentinel value to signal the end of input; for example, 0 or -1 or some other otherwise invalid value.