views:

271

answers:

3

I have this program in c++:

#include <iostream>
using namespace std;
int main()
{
char buf[50];
cin.getline(buf,49);
system(buf);
return 0;
}

When I run and compile it and type for example "helo", my program prints the error:

  "helo" not found.

Can I stop this error from being displayed? Is there any way to disable the error from the system command?

+4  A: 

Are you on linux? Try typing "./hello"

If this works, the reason is that the current directory (".") is not in the search path. You must indicate that the compiled program is "there" in the directory.

Alternatively, you can do something like

export PATH=$PATH:.

This adds "." (current directory) to the search path.

If you are on windows, try "hello.exe"

Helltone
Don't forget to replace ./hello by .\hello.exe if you are under Windows.
daniel
I don't think the OP's concern is with the command being invalid; the OP is trying to block that error message from being displayed.
Ates Goral
No need for ".\" before "hello.exe" on windows, because "." is always on search path.
Helltone
+8  A: 

You can't change the way system displays errors. C and C++ put very little to no requirements on implementations in that regard, so that large parts of it are left unspecified, to allow them to be as flexible as possible.

If you want more precise control, you should use the functions of your runtime library or operation system interface. Try execvp (see man execvp) in linux/unix or the CreateProcess function for windows systems, which uses the Windows API that allows great control over error handling and other stuff.

Johannes Schaub - litb
+2  A: 

If you're on Linux, can you try redirecting the error output to the null device?

strcat(buf, "2> /dev/null");
system(buf);
Ates Goral