How do I run my code from the command line? - c++

i have following code
#include <iostream>
using namespace std;
int main(int argc,char arg[]){
int a=arg[1];
int b=arg[2];
int c=a+b;
cout<<c<<endl;
return 0;
}
i am using windows 7 microsoft visual c++ 2010
how run it from command line?

Open a command prompt from the Start Menu. Use the CD command to change directories to where your exe is. type the name of your exe followed by the arguments.
foo.exe 1 2
or just
foo 1 2
Expect the output (once you've fixed your numerous code errors):
3

Once you compile this you get an executable. Navigate to the directory containing the executable and run it.

Go to google and look for a windows console tutorial. You need to start it from the console. Alternatively you can assign command line in the project properties. I'd recommend learning to do both.
BTW, this code almost certainly does not do what you think it does.

The compiled output of your program will be in the Debug or Release folder inside the solution folder (at least with default project settings). Just change to that directory and run the .exe file.

Open the Visual Studio Command Prompt (you can find it in the Start Menu)
cd to your source file directory
type:
cl.exe <your file name>.cpp
It will create a file .exe

Once your code is setup properly it would be something like this.
MyApp 2 3
Or similar

Navigate to the directory where the executable (.exe) is located. Then type the executable's name followed by two integer parameters.
C:\TestProg\> TestProg 5 6
The problems in your original example are corrected here:
#include <iostream>
#include <sstream>
int main(int argc, char *arg[])
{
std::stringstream sa;
std::stringstream sb;
int a;
int b;
int c;
if (argc >= 3)
{
// Convert string parameter into an integer.
sa.str(arg[1]);
sa >> a;
if (!sa)
{
return 1; // error
}
// Convert string parameter into an integer.
sb.str(arg[2]);
sb >> b;
if (!sb)
{
return 1; // error
}
}
else
{
return 1; // error
}
c = a + b;
std::cout << c << std::endl;
return 0;
}

Related

Why won't header file change the contents?

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream archivo("saludos.txt",ios::in|ios::out); // Abrir y Leer
char caract;
int cont=0;
while (!archivo.eof())
{
archivo.seekg(cont,ios::beg);
caract=archivo.get();
if (caract=='A')
{
archivo.seekp(cont,ios::beg);
archivo<< 'O';
}
cont++;
}
archivo.close ();
}
i'm using this code but when i build and run it, nothing happens in the file saludos.txt There isn't even a response on the console application. anybody know why? i'm using codeblocks and i also have #include fstream
I tried your code in my environment and it works just fine, it replace all 'A' characters with '0'.
I think your problem is with Codeblocks, if you create a new project and want to use file with the relative path in your project, you have to go to Project -> Properties -> Build targets and change the "Executing Working Dir" to your project's folder.
Or you cant try with a absolute file name with full system path first.

How to use file strings as commands in c++

I am trying to make a program on Windows 10 using Visual Studio 2015 that would sim-link certain files to certain locations. I am trying to make a text file with the location of the files, and the sim-link destination to use.
This is an example of the file data that would be in the properties.txt file:
FileLocation: "Z:\Folder\file.txt"
FileMkdirLocation: "Z:\Folder2\file.txt"
I want to use something like system(mkdir "sim-link_file_location" "file_location") by changing the data that is in properties.txt. I want to be able to add more than 1 file, without recompiling the program and writing each command for each file, one by one.
The problem is that I don't know how to make the commands use the data in the file.
EDIT: I managed to find out a way, but I get errors when compiling the program. I use this code:
#include <iostream>
#include <fstream>
#include <string.h>
#include <stdlib.h>
using namespace std;
//initialization of Properties File used
ifstream PropertiesFile ("PropertiesFile.txt");
int main()
{
//initialization of variables used
int input_option;
char FileLocation[256], Command[]="mklink ";
// string FileLocation, Command;
PropertiesFile >> FileLocation;
/* switch (input_option)
{
case "add all mods":
}
*/
cout << "FileLocation: " << FileLocation;
cout << endl;
strcat(Command, FileLocation);
Command[strlen(FileLocation)] = '\0';
cout << Command;
cout << endl;
//system(command);
system("pause");
return 0;
}
I know that i haven't used all variables yet.
It tells me that "strcat" is deprecated and to use "strcat_s" instead, and when i replace it with that, I get
"Debug Assertion Failed - Expression: (L"Buffer is too small" && 0)"
I had to make the "Command" char bigger than "FileLocation" because then strcat_s would not be able to copy the content. After that the program worked fine, and there were no other Assert Errors.
The command to create a soft link in linux is: ln -s <source> <destination>
You can use this in a system(""); call, BUT before you continue in your code, you will have to make sure that the kernel finished executing this command.
After that you can read the link as if it was the original file.

Xcode reading chars from file in c++

I have the following code to read a character from a file:
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, const char * argv[])
{
ifstream f("text.txt");
char c;
f.get(c);
cout << c << endl;
return 0;
}
and my text.txt file contains:
hello world!
However, when I run this on Xcode, I get an inverted question mark as the output.
It works fine on terminal, but not on Xcode. Does anyone know why this happens?
I'm using Xcode to debug some code, but I cant do that anymore because this problem is causing a lot of other errors in my program.
Your text.txt file will not be at the executable path.
Go to your Build Phases - > Copy Files -> Add Your text file
Make sure that:
Destination should be Products Directory
Copy only when installing should be unchecked

Run .exe file of C code using Eclipse

I've make a very simple basic code in C language using Eclipse IDE.
Eclipse details:
Eclipse IDE for C/C++ Developers
Version: Juno Service Release 2
Build id: 20130225-0426
Here is the code:
#include <stdio.h>
int main( int argc, char ** argv ) {
printf("Hello, World!\n");
return 0;
}
Runs successfully in Eclipse, it generates .exe & .o file in Project/Debug directory. I am trying to run that .exe file but it is not working.
Eclipse acts as if it ran the program very quickly and then terminates it. Window appears, but nothing happens when I run the .exe. It just looks like a flash of a dialogue box.
What should be the problem? I don't want to change the IDE and I've already tried these two things:
Eclipse CDT won't run compiled exe files
eclipse won't run my exe file
run the program from the command prompt window. If you simple double click the exe file .. it just runs the program and shuts out in an instant. You won't have any time to see it.
Run it through a cmd window by navigating to the directory and doing ./yourexefile
Or a terrible way to do this with double click is to do this :
#include <stdio.h>
int main( int argc, char ** argv ) {
int n;
printf("Hello, World!\n");
scanf("%d",&n); // this will force the execution window to stay open until you put in some input
return 0;
}
You could also do:
#include <stdio.h>
#include <stdlib.h>
int main( int argc, char ** argv ) {
printf("Hello, World!\n");
system("pause");
return 0;
}
Another way ( more aesthetic ):
#include <stdio.h>
int main( int argc, char ** argv ) {
printf("Hello, World!\n");
printf(" Press enter to exit\n");
getchar();
return 0;
}
Windows is opening a command prompt for your program, running your print statement, and then closing the window (because your function is over).
If you want to see the result of your program, run the command prompt, navigate to the directory of your .exe file, and run it from there.
You should also try this:
Right click on your project name in the Project Explorer view, then go to Run As and click on Local C/C++ Application

finding out the path to a file at runtime

In a program I open a file say file.dat at runtime. The problem is when i run the executable it expects the file to be in the directory from where it is executed. I want the program to look into the same directory where the executable is present. What modifications should I make in my program (or in the build system).
For example consider this program:
int main()
{
std::ifstream ip("file.dat");
// do something.
return 0;
}
I am working on Ubuntu with g++-4.6 compiler and CMake build system. Since the project supports out-of-source build that means the program executable can be anywhere depending upon the directory where the cmake was invoked from.
Thanks for the help...
On many systems, the argv[0] parameter will have the path used to execute the program. Whether or not this is the full path of the program depends on how it was invoked.
int main (int argc, char *argv[]) {
std::string progname(argv[0]);
std::string datafile;
if (progname.find_last_of('/') != std::string::npos)
datafile = progname.substr(0, progname.find_last_of('/')+1);
datafile += "file.dat";
std::ifstream ip(datafile.c_str());
//...
}
On Linux reading /proc/self/exe is the best way to go.
char app_path[1024];
ssize_t len = ::readlink("/proc/self/exe", app_path, sizeof(app_path)-1);
if (len != -1) {
app_path[len] = '\0';
} else {
// handle error
}
For other OS, see: https://stackoverflow.com/a/1024937/105015