This is my code :
#include <iostream>
using namespace std;
int main (int argc, char* argv[])
{
int frstNumb = atoi (argv[1]);
int scndNumb = atoi (argv[2]);
int sum = 0;
sum = frstNumb + scndNumb;
}
Okay, now its working for integers. What do I must do so I can put e.g. "2.5 and 1.2" in my parameters? This program won't calculate that kind of numbers. Help?
Thanks
The arguments are always passed as strings. First of all, change the main function declaration to
int main (int argc, char* argv[])
Note that the return value of main MUST be int, otherwise it is nonstandard.
Second convert argv[1] and argv[2] to integers with either atoi , which, to my taste, is a bit C-ish, although the simplest, or by boost::lexical_cast
e.g.
int i1 = atoi(argv[1]); //#include <cstdlib>
int i1 = boost::lexical_cast<int>(argv[1]); //#include <boost/lexical_cast.hpp>
Yep-- you want atoi().
int frstNumb = atoi(argv[1]);
int scndNumb = atoi(argv[2]);
I'd suggest googling atoi() to see how it works, it will probably help you in the future.
argv[1] and argv[2] are strings. When you do the sum, wrap them with atoi() calls so they are parsed and converted to integers.
Thanks to Mark Loeser and walkingTarget
Your declaration of main() should be:
int main(int argc, char **argv)
or
int main(int argc, char *argv[])
main() should always return an int, and argv should always be an array of strings.
As suggested in other answers, you first need to change declaration of function main - argc represents total number of arguments passed to it and argv is an array of arguments themselves (each argument is an element in array; first element - argv[0] - is path to this executing binary! argv[1] is actually first argument from a command line).
Both in C and C++ you can use atoi or sscanf functions but in C++ you should take advantage of STL stringstream's conversion capabilities:
#include <iostream>
#include <sstream>
using namespace std;
int main(int argc, char* argv[])
{
if(argc != 3)
{
cerr << "Invalid number of operands" << endl;
return 1;
}
int n1 = 0;
int n2 = 0;
stringstream ss;
ss << argv[1];
ss >> n1;
ss.clear();
ss << argv[2];
ss >> n2;
int sum = n1 + n2;
return 0;
}
Related
#include<stdio.h>
#include <string>
#include <stdint.h>
#include<sstream>
#include <stdlib.h>
using namespace std;
string IntToString(int&);
int main()
{
char output[45] = "0";
int str = 0;
char enc[8] = "0";
int enc1[1] = { 0 };
int arrayLength = sizeof(enc1) / sizeof(enc1[0]);
string strs;
for (int i = 0; i <= 100000; i++)
{
int enc1[1];
enc1[0]={ i };
for (int i = 0; i < arrayLength; i++)
{
int& temp = enc1[i];
strs+= IntToString(temp);
enc == strs.c_str();
}
if (atoi(enc)+46*2 == 3251)
{
output == enc;
}
}
printf("%s", output);
}
string IntToString(int& i)
{
string s;
stringstream ss(s);
ss << i;
return ss.str();
}
This is what I want to convert an integer array into a string by continuously increasing, and then convert the string into a number according to the atoi function as a function,I've looked at tutorials on using stoi and I'm not sure what I'm doing wrong. I would appreciate it if you could help me
You code has a lot of problems...
As for your question, if you want to convert an integer into a string, just use std::string your_string = std::to_string(you_integer);.
Then some of the problems that you have:
enc == strs.c_str(); <- the operator == is not the assignment operator. What you do here is that you compare two pointers, that is probably not what you intended, because you don't even check the result of the comparison.
Don't use the loop index i in a nested loop when it is already in use.
Don't use char arrays in C++ unless you have an explicit reason to use it. Even if you are worried about performance, for small strings you can look at std::string as a char array. And you cannot have large strings, because the largest possible integer value represented as a string still counts as a small string.
If you have arrays with constant size, use #define ARRAY_SIZE 15 or something like this rather than what you did.
Don't pass primitive types by reference if you don't have to. As far as I know, only double and long long are larger (on most platforms) than a reference, so you won't gain anything from passing by reference. On the contrary, the optimizer won't like you if you use unnecessary aliasing.
I have to say, I am not sure that I understood your goal correctly. But as I understood it, you want to convert an integer array into a string then to an integer. I am not quiet sure why you would want to do that, but that's on me.
The following code does what I think you wanted. It converts an integer array into an integer by first converting it into a string. But even so, you cannot increase the array size much, because std::stoi will throw an std::out_of_range exception when the number in the string would be too large for an integer.
#include <string>
#include <iostream>
#define ARRAY_SIZE 9
int int_arr_to_int (const int * const arr) {
std::string str;
for (size_t i = 0; i < ARRAY_SIZE; ++i) {
str += std::to_string(i);
}
return std::stoi(str);
}
int main(int argc, char* argv[]) {
int arr[15] = { 0 };
for (size_t i = 0; i < ARRAY_SIZE; ++i) {
arr[i] = i;
}
std::cout << int_arr_to_int(arr) << std::endl;
return 0;
}
I've a program which is taking input from command-line and using them ahead. All this time the inputs were given separately after the invocation command eg ./a.out 1 2 3 4 5 and it was quite easy to use them (lets just sum them for the moment) -
#include <iostream>
#include <cstdlib>
int main(int argc, char **argv) {
int sum = 0;
for(int i = 1; i < argc; ++i) {
sum += std::atoi(argv[i]);
}
std::cout << sum << std::endl;
}
but now the input format has changed to ./a.out "1 2 3 4 5" and this method does not works correctly. I tried to take "1 2 3 4 5" to a string but then I cannot get the integers out of it. Nor can I think of any other solution at this moment. Is there any elegant method to take them out of argv without too much complexity?
You need to split the string. You can do this for example using string streams:
#include <iostream>
#include <sstream>
int main(int argc, char **argv) {
int sum = 0;
for(int i = 1; i < argc; ++i) {
std::istringstream iss(argv[i]);
for (int n; iss >> n;) sum += n;
}
std::cout << sum << std::endl;
}
I wanna sort an array of command line arguments. All arguments are integer.
Here is my code, but it does not work.
#include <iostream>
using namespace std;
int main (int argc, char *argv[]) {
for (int i=0; i<argc-1; ++i) {
int pos = i;
for (int j=i+1; j<argc; ++j) {
if (argv[j] - '0' < argv[pos] - '0') {
pos = j;
}
}
char *tempt = argv[i];
argv[i] = argv[pos];
argv[pos] = tempt;
}
for (int i=0; i<argc; ++i) {
cout << argv[i] <<endl;
}
}
After compiling, when I called ./a.out 4 3 2 1, it still printed 4 3 2 1 to the screen instead of 1 2 3 4.
What's wrong?
Thanks in advance.
Try std::sort from <algorithm> with a custom comparator
std::sort(argv, argv + argc, [](char * const & a, char * const & b) {
return atoi(a) < atoi(b);
});
In modern c++ you can use auto types for lambdas. For string to int convertion I would prefer stoi function over atoi (you can look for differences here). Also worth noting that first argument (argv[0]) is a program name, e.g. ./a.out, so you need to skip it from sorting. Final result could be looks like this:
#include <algorithm>
#include <iostream>
#include <iterator>
#include <string>
int main (int argc, char *argv[]) {
std::sort(argv + 1, argv + argc, [](auto l, auto r){ return std::stoi(l) < std::stoi(r); } );
std::copy(argv + 1, argv + argc, std::ostream_iterator<const char*>(std::cout, " "));
}
If all of command line arguments a unsigned number with fixed digits count you could also sort them like string, i.e. without explicit converting to numbers via std::stoi. In this case std::vector<std::string> could be used:
std::vector<std::string> v(argv + 1, argv + argc);
std::sort(v.begin(), v.end());
There is no need to use lambda or another custom comparator for std::sort.
i am trying to use command line argument in Linux(Ubuntu) in c++ . but it generates run time error : segmentation fault.this program runs with no error in windows .here is my code
#include<iostream>
using namespace std;
int main(int argc , char **argv){
char **ss;
for(int i=0;i<argc;i++){
ss[i] = argv[i];
}
for(int i=0;i<argc ;i++)
cout<<ss[i];
return 0;
}
what is wrong with this code. please help me . thanks in advance.
Your program has undefined behaviour because you did not initialize pointer ss and allocate memory where you are going to copy elements pointed by argv
char **ss; // What value does it have?
for(int i=0;i<argc;i++){
ss[i] = argv[i];
You could do the following way
char **ss = new char *[argc];
for(int i=0;i<argc;i++){
ss[i] = argv[i];
The better way is to use std::vector<std::string>. In this case you could also copy not only pointers to arguments but and also the arguments. For example
#include<iostream>
#include <vector>
#include <string>
int main(int argc , char **argv)
{
std::vector<std::string> v( argv, argv + argc );
for ( const std::string &s : v ) std::cout << s << std::endl;
return 0;
}
If your compiler does not support the range based for statement then you can substitute it for
for ( std::vector<std::string>::size_type i = 0; i < v.size(); i++ )
{
std::cout << v[i] << std::endl;
}
As already answered, you haven't allocated any memory for ss.
Since you're using c++ and not c, you should have the c++ standard library at your disposal:
std::vector<std::string> ss;
ss.reserve(argc); // not necessary
for(int i=0;i<argc;i++)
ss.push_back(argv[i]);
Use the following declaration for ss
#include<iostream>
using namespace std;
int main(int argc , char **argv){
char *ss[argc]; // <--allocate argc count of pointers
for(int i=0;i<argc;i++){
ss[i] = argv[i];
}
for(int i=0;i<argc ;i++)
cout<<ss[i];
return 0;
}
This question already has answers here:
What does int argc, char *argv[] mean?
(12 answers)
Closed 9 years ago.
I was messing around with projects in C/C++ and I noticed this:
C++
#include <iostream.h>
int main (int argc, const char * argv[]) {
// insert code here...
cout << "Hello, World!\n";
return 0;
}
and
C
#include <stdio.h>
int main (int argc, const char * argv[]) {
// insert code here...
printf("Hello, World!\n");
return 0;
}
So I've always sort of wondered about this, what exactly do those default arguments do in C/C++ under int main? I know that the application will still compile without them, but what purpose do they serve?
They hold the arguments passed to the program on the command line. For example, if I have program a.out and I invoke it thusly:
$ ./a.out arg1 arg2
The contents of argv will be an array of strings containing
[0] "a.out" - The executable's file name is always the first element
[1] "arg1" - The other arguments
[2] "arg2" - that I passed
argc holds the number of elements in argv (as in C you need another variable to know how many elements there are in an array, when passed to a function).
You can try it yourself with this simple program:
C++
#include <iostream>
int main(int argc, char * argv[]){
int i;
for(i = 0; i < argc; i++){
std::cout << "Argument "<< i << " = " << argv[i] << std::endl;
}
return 0;
}
C
#include <stdio.h>
int main(int argc, char ** argv){
int i;
for(i = 0; i < argc; i++){
printf("Argument %i = %s\n", i, argv[i]);
}
return 0;
}
If you want to accept arguments through commandline ,then you need to use the arguments in the main function .argc is the argument count and array of charecter pointers list the arguments.
refer this link http://www.cprogramming.com/tutorial/c/lesson14.html
Those are for command-line arguments. argc is the number of arguments, and the arguments are stored as an array of null-terminated strings (argv). Normally, a program with no command-line arguments passed in will still have one stored in argv; namely, the name used to execute the program (which won't always be there, depending on how the program is executed, but I can't remember what the circumstances are for that).
argc and argv are how command line arguments are passed to main() in C and C++.
argc will be the number of strings pointed to by argv, this will usually be one more than the number of arguments you pass from terminal, as usually the first is the name of the program.