Storing the output of a system command that uses an awk loop

Hello all you lovely people! :-)

I am in the means of beginning to learn C++. I just have a quick question (and I imagine you get a lot 'debug' me questions.. yes I'm sorry!!)

I can't get this to compile.

My syntax all looks good (at least to me).

I know the problem lies on line 8.

'funfun' is just a simple text file.

Any ideas? :-)




1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;

char main ()
{
 i=system ("cat funfun | awk '{ for (i=1; i<10; i++) print $i }'");
  cout << i << endl;

 return 0;
}
Last edited on
You haven't declared variable i
Thank you kbw, much appreciated.

I also needed to change my main function type to int.

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;

int main ()
{
 char i;
 i=system ("cat funfun | awk '{ for (i=1; i<10; i++) print $i }'");
  cout << i << endl;

 return 0;
}


Why did I need to change my main function type to 'int' for it to compile? I mean the data that it contains is just going to be characters. (just curious)

Thank you very much.
The short answer is becase the standard says so.

Your program can return a code to it's caller by the value returned from main. For example, cat and awk in your example, return codes to the shell which allow the shell to determine if an error occurred.

Normally, zero means no error.
The return type of the function doesn't say anything about the data the function contains, or even what the function does -- only what it returns.

But anyway the reason main() has to be int is because "that's the way it is". That sounds like a lame answer but pretty much what it boils down to is that the compiler needs to know where to "start" your program from (where the "entry" point is). It looks for one of the two functions:

int main()
or
int main(int argc,char* argv[])

Since char main() is a different function because the return type is different, the compiler (or really, the linker) won't see it as one of the above two functions, and thus won't find a suitable entry point for your program.

edit -- I'm too slow ;_; heh
Last edited on
Topic archived. No new replies allowed.