Sep 2, 2014 at 7:13pm UTC
When I add it to my code and try to compile it gives me error...
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
#include <iostream>
#include <fstream>
#include <istream>
#include <stdio.h>
int main()
{
FILE* fp;
int countLines = 1;
int i;
int columns = 0;
fp = fopen("filename.txt" , "r" );
if (fp == NULL)
{
printf("We can't open the file." );
fclose(fp);
return 1;
}
else
{
while ((i=fgetc(fp))!=EOF)
{
if (i == '\n' )
countLines++;
}
printf(">Numrows filename.txt: %d\n" , countLines);
}
while ((i=fgetc(fp))!=EOF)
{
if (i == ' ' )
++columns;
}
else if (i == '\n' )
{
countLines++;
cout << "line " << countLines <<" has " << columns << " columns.\n" ;
columns = 0; // reset for next line.
}
return 0;
}
Last edited on Sep 2, 2014 at 7:56pm UTC
Sep 2, 2014 at 9:31pm UTC
You need a {
on line 30. There may be other errors, that was off the top of my head. You should be able to figure it out from my example though.
Sep 2, 2014 at 9:44pm UTC
So I added your code in a new file to fix error....
now I get this
work.cpp:24:4: error: ‘cout’ was not declared in this scope
cout << "line " << countLines << " has " << columns << " columns.\n";
^
This was the code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
#include <iostream>
#include <fstream>
#include <istream>
#include <stdio.h>
int main()
{
FILE* fp;
int countLines = 1;
int i;
int columns = 0;
fp = fopen("filename.txt" , "r" );
if (i == ' ' )
{
++columns;
fclose(fp);
}
else if (i == '\n' )
{
while ((i=fgetc(fp))!=EOF)
{
countLines++;
cout << "line " << countLines << " has " << columns << " columns.\n" ;
columns = 0; // reset for next line.
}
} return 0;
}
Last edited on Sep 2, 2014 at 9:47pm UTC
Sep 2, 2014 at 10:03pm UTC
This is just showing me number of rows..which is 4
Sep 2, 2014 at 10:09pm UTC
Why do you include fstream and istream, when you don't use them at all?
Alternatively, why do you use stdio, when you could use streams?
The using namespace std;
is not recommended. The library writers have worked hard to get the library within namespace, for a good reason.
If you refer to cout only once, you can easily write std::cout.
If you refer multiple times, you can add using std::cout;
Sep 2, 2014 at 10:12pm UTC
Isnt fstream used for adding to the text file??
Sry not sure bout istream tho