How do you execute a command line program with arguments from a c++ program? This is what I found online:
http://www.cplusplus.com/forum/general/15794/
std::stringstream stream;
stream <<"program.exe "<<cusip;
system(stream.str().c_str());
But it doesn't seem to accept an actual program location, so I am not sure how to apply this. My hope was to have something like this:
std::stringstream stream;
stream <<"C:\Tests\SO Question\bin\Release\HelloWorld.exe "<<"myargument";
system(stream.str().c_str());
This gives several warnings related to the backslashes - and the program does not work. Is it expecting you to have the program in some specific location?
This is the output I get in the console:
'C:\Tests' is not recognized as an internal or external command,
operable program or batch file.
ADDENDUM:
So based on Jon's answer the correct version for me looks like this:
#include <iostream>
#include <cstdlib>
#include <sstream>
#include <cstring>
int main(int argc, char *argv[])
{
std::stringstream stream;
stream << "\"C:\\Tests\\SO Question\\bin\\Release\\HelloWorld.exe\""
<< " " // don't forget a space between the path and the arguments
<< "myargument";
system(stream.str().c_str());
return 0;
}
First of all, you should use double backslashes in literal strings whenever you want a single backslash to appear in the actual string value. This is according to the language grammar; a conforming compiler could do worse than simply warning about this.
In any case, the problem you are experiencing is due to the fact that paths containing spaces must be enclosed in double quotes in Windows. Since the double quotes themselves need to be escaped inside a C++ string literal, what you need to write is
stream << "\"C:\\Tests\\SO Question\\bin\\Release\\HelloWorld.exe\""
<< " " // don't forget a space between the path and the arguments
<< "myargument";
This gives several warnings related to the backslashes
I believe \ is an escape character in C++ using \\ instead will probably solve this problem.
Related
I tried compiling the following program on XCode on my Mac, and I get these errors:
*Non-ASCII charactes are not allowed outside of literals and identifiers. Fix it: Delete ""
*Use of undeclared identifier 'Hello'
#include <iostream>
using namespace std;
int main()
{
cout << “Hello there world!”;
return 0;
}
This program is literally verbatim from the textbook, "A First Book of C++: An Introduction to Programming" so I'm not sure why it would not work. Is this a Mac vs. PC issue?
The "pretty quotes" copied from your textbook are not valid characters.
Change:
cout << “Hello there world!”;
// ^ ^ These characters are not correct.
To:
cout << "Hello there world!";
The editor you use to type code must not be one that replaces the characters you type with characters that might look nicer.
It seems that you are using non-ASCII double quotes
try with this string (cut and paste) "Hello there world", note the different leading apostrophes.
Try using the Code::Blocks compiler
http://www.codeblocks.org/
Picking up C++ and having a go at it on OS X 10.9 using XCode 5.0.2 and using Alex Allain as reference.
The following code compiles just fine and outputs correctly
#include <iostream>
#include <string>
using namespace std;
int main()
{
std::string user_first_name = "test";
std::cout << user_first_name << "\n";
return 0;
}
When I add a getline function, code appears to compile but with no output.
#include <iostream>
#include <string>
using namespace std;
int main()
{
std::string user_first_name = "test";
std::getline( std::cin, user_first_name, '\n' );
std::cout << user_first_name << "\n";
return 0;
}
In fact debug navigator has memory filling up with bars (although actual memory use is fixed at 276 KB). Why am I getting stumped on such a simple thing/concept?
I did a bit of digging around and its quite likely this is related to a text encoding issue. I'm using defaults which is Unicode (UTF-8). Encoding is not something I'm familiar with, never something I had to deal with when learning on Windows. How do I get past this?
I can't comment regarding the use of XCode or OS X, but it was my understanding that std::cin always gives you a narrow (single-byte) character stream. In Windows (at least with Visual Studio), I think it works whether you compile for UTF8 (single-byte for all ASCII characters) or UTF16 (2-bytes for all ASCII characters). The runtime library presumably does the conversion for you as necessary.
I'm not sure what "filling up with bars" means, but maybe it's just that you're looking at uninitialized memory. If you think that it is an encoding issue, perhaps try using wstring/wcin instead of string/cin and see if that helps.
I stumble on the following compilation error in C++ with g++ compiler:
error on line line 1 with message:
invalid preprocessing directive #a
(with a caret above the character a) which is followed by another,probably consequent, error on line 4 with message:
cout was not declared in this scope.
The editor i am using is Code blocks 10.05 with mingw.I tried removing .h extension from the iostream file include statement;switching among different File encoding options;and replacing the angular bracket with single quotes and double quotes as well.i am stuck on it.Pardon if it is a duplicate(although i went through several already asked questions in relevance).
The following code illustrates the problem:
#include <iostream.h>
int main()
{
cout<< "abc"+8;
cout<< "def"+4;
cout<< "ha";
return 0;
}
cout exists within the namespace std
So either
#include<iostream>
//...
std::cout << "abc" << 8;
//...
or
#include<iostream>
using namespace std;
//...
or
#include<iostream>
using std::cout;
//...
I tend to prefer the 1st if I'm only using it once or twice, The second if I'm using a lot of different pieces from a namespace (and only in a cpp file), or the third if I'm only using a piece or 2 from a namespace but using the same couple many times.
Additionally as stated in the comments, don't use the 2nd one in headers. See: "using namespace" in c++ headers
Also, you have an invalid character in your #include. You can see it in a hex editor or Note how stackoverflow doesn't highlight them the same:
#include<iostream>
#include<iostream>
Fully working code:
#include<iostream>
using std::cout;
int main()
{
cout << "abc" << 8;
cout << "def" << 4;
cout << "ha";
return 0;
}
Produces the following output abc8def4ha after I corrected for trying to add 8 to a char*
You have to use std::cout, which means that the "cout" keyword is part of the standard library.
The "invalid directive" error is caused by some invisible Unicode characters in the #include directive; perhaps you copied this from a website that embedded some formatting characters in the code. They can be seen in the question, if you look at the source in a hex editor. That error should be fixed by deleting and retyping the #include line.
You'll probably have other errors, since the code is fifteen years out of date; most modern compilers don't provide pre-standard libraries. These days, the standard library headers don't have a .h extension:
#include <iostream>
and nearly all the names they declare are scoped inside the std namespace:
std::cout << "ha";
Finally, "abc"+8 doesn't do anything sensible. The string literal is an array of four characters, and +8 tries to give you a pointer to the ninth character, which doesn't exist. The result is undefined behaviour.
If you want to print "abc" followed by "8", then you want:
std::cout << "abc" << 8;
Try using it like this:-
#include <iostream>
using std :: cout;
cout is the part of std library
If you've got caret above a, try retyping your #include.
You might accidentally type alternative i which looks similar but has different code.
Suggestions about std:: are only relevant for the second error you're getting.
I also didn't fully understand what you were trying to achieve with "abc"+8.
I want to output a line into a .plt file that says "one-D Hydro" with the double quotation marks and so far I have this problem.
#include <cstdlib>
#include <fstream>
using namespace std;
int main()
{
fstream gnuplot_file;
gnuplot_file.open ("sod.plt");
gnuplot_file<<"set title"<< ""one-D Hydro""<<std::endl;
gnuplot_file.close();
system("gnuplot.exe sod.plt");
return 0;
}
Line 11 will not allow it to compile because I can't seem to close the statement. The error is just as useless by the way.
gnuplot_call.cpp|11|error: expected ';' before 'one'|
With C++03 (or even C) use backslashes to escapes double-quotes in string literals:
gnuplot_file << "set title" << "\"one-D Hydro\"" << std::endl;
Notice that gnuplot may require you to also escape some characters, e.g. if you wanted the title to contain quotes!
With C++11 you could use raw string literals, e.g.
gnuplot_file<< R"*(set title "one-D Hydro")*" << std::endl;
BTW, you could be interested by popen(3) and pclose, if your operating system and C++ library provides them. You would just popen the gnuplot process and send commands to it, finally pclose-ing it.
Try to include escape character [i.e.,back slash] in the code where you are trying to add double quotes.
For example:
"\"one-D Hydro\""
btw why are you using std:: once you have defined namespace for it you can directly use endl.
I know there's been a handful of questions regarding std::ifstream::open(), but the answers didn't solve my problem. Most of them were specific to Win32, and I'm using SDL, not touching any OS-specific functionality (...that's not wrapped up into SDL).
The problem is: std::ifstream::open() doesn't seem to work anymore since I've switched from Dev-C++ to Code::Blocks (I've been using the same MinGW-GCC back-end with both), and from Windows XP to Vista. (It also works perfectly with OS X / xcode (GCC back-end).)
My project links against a static library which #includes <string>, <iostream>, <fstream> and <cassert>, then a call is made to functionality defined in the static library, which in turn calls std::ifstream::open() (this time, directly). Following this, the stream evaluates to false (with both the implicit bool conversion operator and the good() method).
Code:
#include "myStaticLibrary.hpp"
int main(int argc, char **argv)
{
std::string filename("D:/My projects/Test/test.cfg");
std::cout << "opening '" << filename << "'..." << std::endl;
bool success(false);
// call to functionality in the static library
{
std::ifstream infile(filename.c_str());
success = infile.good();
// ...
}
// success == false;
// ...
return 0;
}
stdcout.txt says:
opening 'D:/My projects/Test/test.cfg'...
When I open stdcout.txt, and copy-paste the path with the filename into Start menu / Run, the file is opened as should be (I'm not entirely sure how much of diagnostic value this is though; also, the address is converted to the following format: file:///D:/My%20projects/test/test.cfg).
I've also tried substituting '/'s with the double backslash escape sequence (again, slashes worked fine before), but the result was the same.
It is a debug version, but I'm using the whole, absolute path taken from main()'s argv[0].
Where am I going wrong and what do I need to do to fix it?
Please create a minimal set that recreates the problem. For example, in your code above there's parsing of argv and string concatentation, which do not seem like a necessary part of the question. A minimal set would help you (and us) see exactly what's going wrong, and not be distracted by questions like "what's GetPath()?".
Try to do this instead of assert(infile.good()):
assert(infile);
I have overseen the importance of the fact that the function in question has close()d the stream without checking if it is_open().
The fact that it will set the stream's fail_bit (causing it to evaluate to false) was entirely new to me (it's not that it's an excuse), and I still don't understand why did this code work before.
Anyway, the c++ reference is quite clear on it; the problem is now solved.
The following code:
#include <string>
#include <iostream>
#include <fstream>
#include <assert.h>
using namespace std;;
int main(int argc, char **argv)
{
std::string filename("D:/My projects/Test/test.cfg");
std::cout << "opening '" << filename << "'..." << std::endl;
std::ifstream infile(filename.c_str());
assert(infile.good()); // fails
return 0;
}
works fine on my Windows system using MinGW g++ 4.4.0, if I create the required directory structure. Does the file test.cfg actually exist? If you are opening a stream for input, it wioll fail if the file is not there.
Edit: To remove any DevC++ to CB issues:
build using command line only
make sure you rebuild the static library too