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.
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)
I'm writing a C++ program that converts a decimal number to binary and hexadecimal.
The problem is that for some reason it concatenates the number "1875954912" to both representations every time.
I've tried a bunch of things - mainly changing up how the program calculates numArrayLength and the for-loop in my decToBase function, but I haven't been able to figure out why this happens yet.
The program is not complete by the way - it doesn't turn integers bigger than 9 into letters for the hex representation yet, but that's not my main concern right now.
Here is my code:
#include <iostream>
#include <cmath>
using namespace std;
int howManyBitsNeeded(int someNum, int base) {
int numOfDivisions = 0;
while (someNum != 0) {
someNum = floor(someNum / base);
numOfDivisions += 1;
}
return numOfDivisions;
}
int decToBase(int someNum, int base) {
int bitsNeeded = howManyBitsNeeded(someNum,base);
int numArrayLength = bitsNeeded;
int numArray[bitsNeeded];
while (bitsNeeded > 0) {
numArray[bitsNeeded] = (someNum % base);
someNum = floor(someNum / base);
bitsNeeded -= 1;
}
for (int k = (numArrayLength-1); k >= 0; --k) {
cout << numArray[(numArrayLength - k)];
}
}
int main() {
int inpNum;
cout << "Enter your number: ";
cin >> inpNum;
cout << "Binary representation: " << decToBase(inpNum,2) << endl;
cout << "Hexadecimal representation: " << decToBase(inpNum,16);
return 0;
}
And here's what the output looks like:
Enter your number: 25
Binary representation: 110011875954912
Hexadecimal representation: 191875954912
Any help would be greatly appreciated!
Your decToBase is declared as returning an int, but it doesn't actually return anything. Your compiler should warn you about this. Since you're not returning anything here, change its return type to void. Then instead of trying to print its return value, simply call the function without printing it:
std::cout << "Binary representation: ";
decToBase(inpNum, 2); // this already prints the number, no need to pass it to std::cout
std::cout << endl;
std::cout << "Hexadecimal representation: ";
decToBase(inpNum, 16);
std::cout << std::endl;
Or of course you can change the function to return the string that you want to print instead of printing it inside the function.
Also, there's an issue here:
int numArray[bitsNeeded];
This is out of range when you try to access it here:
while (bitsNeeded > 0) {
numArray[bitsNeeded] = (someNum % base);
And also later when you try to print it. To get rid of this off by one error, you have to change this to
numArray[bitsNeeded-1] = (someNum % base);
And in the output change it to
cout << numArray[(numArrayLength - k -1)];
And while you're at it, instead of having it as a VLA (which isn't part of C++ and only works if the compiler tolerates it), I would recommend a vector:
std::vector<int> numArray(bitsNeeded+1); // include <vector> for this to work
Furthermore, note that integer division is already truncated, so unless you plan to support negative numbers later on, you can silence a warning about implicit double to int conversion by changing this:
someNum = floor(someNum / base);
To this:
someNum /= base;
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?";
}
}
I keep getting this error at run-time: "'Int' is not convertible to type 'double'", it displays this as soon as I run the program, but then it quickly disappears and then shows my program. I'm using VC2010. (EDIT: This program is to convert Celsius to Fahrenheit, and to tell if it's hot or not hot.)
#include <iostream>
int convert(int);
int main(void)
{
using std::cout;
using std::cin;
using std::endl;
cout << "Enter the degrees in Celsius: ";
int temp;
cin >> temp;
int degrees = convert(temp);
if(degrees<100)
{
cout << degrees << " is not too hot." << endl;
}
else if(degrees>100)
{
cout << degrees << " is hot." << endl;
}
cin.get();
cin.get();
return 0;
}
int convert(int ctf)
{
return ctf * 1.8 + 32;
}
You should explicitly cast the result of convert method to int to avoid this message.
int convert(int ctf)
{
return (int) (ctf * 1.8 + 32);
}
Since the return type is specified ad int, but the result of the float multiplication is not int, it is showing this message.
However, since you are converting temperatures from Celsius to Fahrenheit, it is better to use double or float values instead of int to yield more accurate and meaningful output.
You are getting a compiler warning informing you of a loss of precision by specifying that convert returns an int while the expression ctf * 1.8 + 32 returns a double as 1.8 is of type double. Arithmetic expressions involving variables of type int and double will promote the resulting type to double. I recommend updating your convert function to:
double convert(double ctf)
If you insist on using integers, make the appropriate cast:
int convert(int ctf)
{
return static_cast<int>(ctf * 1.8 + 32);
}
I think your error is in the convert function, by multiplying a int with a decimal you are automatically converting it to a double. so either return a double, or cast it to a int
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.