I have a sort of calculator in C++ that should accept arguments when executed. However, when I enter 7 as an argument, it might come out to be 10354 when put into a variable. Here is my code:
#include "stdafx.h"
#include <iostream>
int main(int argc, int argv[])
{
using namespace std;
int a;
int b;
if(argc==3){
a=argv[1];
b=argv[2];
}
else{
cout << "Please enter a number:";
cin >> a;
cout << "Please enter another number:";
cin >> b;
}
cout << "Addition:" << a+b << endl;
cout << "Subtaction:" << a-b << endl;
cout << "Multiplycation:" << a*b << endl;
cout << "Division:" << static_cast<long double>(a)/b << endl;
system("pause");
return 0;
}
Wherever did you get int argv[]? The second argument to main is char* argv[].
You can convert these command line arguments from string to integer using strtol or to floating-point using strtod.
For example:
a=strtol(argv[1], nullptr, 0);
b=strtol(argv[2], nullptr, 0);
But you can't just change the parameter type, because the operating system is going to give you your command-line arguments in string form whether you like it or not.
NOTE: You must #include <stdlib.h> (or #include <cstdlib> and using std::strtol;) to use the strtol function.
If you want error-checking, use strtol instead of atoi. Using it is almost as easy, and it also gives you a pointer to the location in the string where parsing terminated. If that points to the terminating NUL, parsing was successful. And of course it is good that you verify argc to make sure the user provided enough parameters, and avoid trying to read missing parameters from argv.
Example of error checking:
char* endp;
a = strtol(argv[1], &endp, 0);
if (endp == argv[1] || *endp) { /* failed, handle error */ }
The function signature is int main(int argc, char *argv[]). argv is an array of string pointers.
If the argument is 7, it will be in the form of a string ("7"). Use atoi() to convert it to the number 7.
Second argument in the main should either either be char* argv[] or char** argv. Then you have to have convert them to int.
Related
I am facing this problem from day 1.
Actually, the book I am reading from has this program written in this way, but when I check it practically on Eclipse IDE, it does not work properly, always showing this error:
invalid conversion from char to const char *
Although I know what the issue is, I don't know how to resolve this problem, and I am facing this problem with every program in which there is some string operation.
The error is with this if statement:
if(!strcmp(str, *ptr[i]))
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
const char *ptr[10] = { "books", "television", "computer", "sports" };
int i = 0;
char str[25];
cout << "\nEnter your favorite leisure pursuit here :" << "\n";
cin >> str;
for (i = 0; i < 4; i++)
{
if (!strcmp(str, *ptr[i]))
{
cout << "\n your favorite pursuit is available here " << endl;
break;
}
}
if (i == 4)
{
cout << "\n\nYour favorite leisure is not available here" << endl;
}
return 0;
}
strcmp() compares two null-terminated const char* strings. But, you are trying to compare a null-terminated char[] string to a single char, hence the error. This is because you are dereferencing the 2nd const char* string to access its 1st char element.
ptr is an array of const char* pointers, so you need to drop the extra * dereference operator when accessing ptr[i], so that you compare the whole string, not just a single character of the string, eg:
if (strcmp(str, ptr[i]) == 0)
There is a problem with my code. It always return an error ISO C++ forbids comparison between pointer and integer[-fpermissive]. Can you help me see what is the problem here and how to solve it?
#include <iostream>
using namespace std;
char x;
int main()
{
cout << "Welcome to the citation machine. What do you want to cite?" << endl;
cin >> x;
if (x == "book")
{
cout << "What is the name of the book?";
}
}
#include <iostream>
char is not a string, it is a character, means an integer (signed between -128 and 127 on most compiler implementations)
If you change the type of x to string it will do what you want
You had a raw C comparison char vs char * which explains the error message
By turning the char into a string you activate the string::operator== which accepts char * as a convenience and performs a string comparison, which is intuitively what you want to do.
My advice is: keep going with C++ and never use char *, malloc or all that C stuff likely to fail, stick to std::string, and use std::string::c_str() to get the string contents as const char * for use with C primitives if needed.
A positive side-effect is that it will avoid the trap of comparing 2 char * types with == operator, which compare pointers and not values.
using namespace std;
string x;
int main()
{
cout << "Welcome to the citation machine. What do you want to cite?" << endl;
cin >> x;
if (x == "book")
{
cout << "What is the name of the book?";
}
}
So i am writing a program that takes in an int, and returns something to do with the bits that represent the int. However, when I put an int in the command line and immediately print it out it, it prints 2.
Why is this happening, and how can I fix it?
~ ./a.out 8
I can only take in one parameter for main:
#include<iostream>
#include<cstdlib>
using namespace std;
void foo (int ii, int x){
static int p;
k= x<<ii;
.
.
}
int main(int x) {
cout << x << endl;
.
.
.
return 0
}
Parameter passing does not work the way you appear to believe it does.
There are precisely two signatures for main that are guaranteed to work:
int main()
and
int main(int argc, char *argv[])
The latter is the one you use when you want to parse command line arguments. Here argc is the argument count, i.e. the number of passed arguments (including the name of the command itself) and the length of argv. argv is an array of C-style strings that holds the arguments.
So, when you call
./a.out 8
then argc is 2, argv[0] is "./a.out", argv[1] is "8", and argv[2] is a null pointer. If you want to use the first command line argument as a number, you have to parse argv[1] with std::istringstream or atoi or similar, as in
#include <iostream>
#include <sstream>
int main(int argc, char *argv[]) {
if(argc < 2) {
std::cerr << "No argument was given.\n";
return -1;
}
std::istringstream parser(argv[1]);
int x;
if(parser >> x) {
std::cout << x << " * 2 = " << x * 2 << '\n';
} else {
std::cerr << "The argument was not a number.\n";
return -2;
}
}
As a side note, because this is not something you can depend upon, this also explains why you get the output 2. When you write
int main(int x) {
x takes the value of argc, and what would have been argv is ignored, for low-level reasons that have to do with the way the arguments are laid out in memory before the jump to main. When you call the program with ./a.out 8, that value is 2, and so x is 2 in your code. This is not guaranteed to work by the C++ standard, but it is likely to happen on all platforms as it did on yours.
I tried to iterate through an integer using a char pointer. My question is: Why is it stored in memory backwards? When I run the code:
#include <iostream>
using namespace std;
int main(int count, char** args)
{
unsigned int number = 0xabcdef12;
cout << "Number:\t\t" << hex << number << endl;
cout << "Iterated:\t";
unsigned char* pointer = (unsigned char*)&number;
for(int i=0; i<sizeof(number); i++)
cout << hex << (unsigned int)pointer[i];
cout << endl;
return 0;
}
The output is:
Number: abcdef12
Iterated: 12efcdab
I want to know if there is a way to force C++ to order the bytes, e.g.:
Number: abcdef12
Iterated: abcdef12
(Extra info: I want to do this because I want to iterate through a struct by byte and write the result to file.)
This is because you're on a "little-endian" system. Some computers, including the x86 ones most of us use, are this way. You can swap the byte order of an int with the standard function htonl(); the result will always be in "network byte order" which is the one you were expecting here.
I'm writing a very basic command line C++ application that takes arguments on execution.
I just started C++ today, and it seems apparent that you can only take char** as the data type for arguments. I want to take two floats as parameters (to add them together later), but I can't seem to cast the character arrays as floats.
I have tried static_cast<float>(argv[0]) and stof(argv[0]) to cast the values, and both give compiler errors (unable to cast and not defined in scope, respectively).
I'm using the Code::Blocks IDE if that answers any questions.
My code:
#include <iostream>
#include <string>
/**
* author: 2mac
*
*/
using namespace std;
void derp();
float getSum(float num1, float num2);
int main(int argc, char** argv)
{
float num1 = static_cast<float>(argv[0]);
float num2 = static_cast<float>(argv[1]);
if (argc != 0 || argc != 2)
cout << "Usage: hello-world [args]\nargs: none OR <num1> <num2> to be added together" << endl;
else
{
switch (argc)
{
case 0:
derp();
break;
case 2:
derp();
cout << num1 << " + " << num2 << " equals " << getSum(num1,num2) << endl;
break;
}
}
return 0;
}
void derp()
{
cout << "Hello, world!\n";
cout << "It's time to lern some C++!" << endl;
}
float getSum(float num1, float num2)
{
return num1 + num2;
}
Using this to convert your input to float number,
double f1, f2;
if (argc == 2)
{
f1 = atof (argv[0]);
f2 = atof (argv[1]);
}
A char** in C++ is just that, an pointer to a pointer to a character, thus not convertable to a float (Or any numeric value for that matter) directly Thus your first example will fail. You can use the intermediary functions atof or strtof (note strtof, not stof, why your second example fails) to convert these values, assuming you are sure they are actually in float form.
You are just converting a char * variable to float by typecasting. It will typecast value of the pointer to float, not the string to float.
You need to use functions such as atof, strtof to convert string to float. Or you can write your own function to to convert string to float.