How to get unsigned int as console argument? - c++

I'm trying to pass an unsigned int value via console argument to my program.
what have I tried yet:
first: check if argc is 2, otherwise error
if there is a second value I tried to convert this value with:
strtoul(argv[1], NULL, 0)
So when I pass "100", i get "1"
What am I doing wrong?
br
Sagi
€: passed a wrong argument to my function, found the mistake, thanks guys

It's a little hard to tell without seeing the actual code but you can use this as a baseline:
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char *argv[]) {
char *pCh;
unsigned long unlong = 42;
// Check enough arguments.
if (argc != 2) {
puts ("Not enough arguments");
return 1;
}
// Convert to ulong WITH CHECKING!
unlong = strtoul (argv[1], &pCh, 10);
// Ensure argument was okay.
if ((pCh == argv[1]) || (*pCh != '\0')) {
puts ("Invalid number");
return 1;
}
// Output converted argument and exit.
printf ("Argument was %ld\n", unlong);
return 0;
}
Transcript follows:
pax> ./testprog 314159
Argument was 314159
If that's not enough to help out, I suggest you post the shortest complete program that exhibits the problem, then we can tell you in excruciating detail what's wrong with it :-)

Your method should work. Alternatively, you can use stringstream:
std::string str(argv[1]);
unsigned long ul;
std::stringstream(str)>>ul;

Related

Using strstr in C MBED, printing result

I'm trying to compare two char arrays and print to the terminal whether or not the string was found.
When I run my code, the output printed returns a load of jibber that's not related to what I specified. I think more memory than I've specified is being printed but I'm not sure why.
Strstr returns a pointer to the beginning index of the found string (if found), null if not. I'm guessing this is what is causing the error - but I thought by only checking if the result was null rather than printing the result would bypass this.
My code:
include "mbed.h"
include "string.h"
char input[] = "Hello mbed";
char value[] = "llo";
int main() {
char * output;
output = strstr(input, value);
bool found = false;
if (output != NULL) {
found = true;
}
printf(found ? "true" : "false");
}
My output:
trueloHello mbed½mà$Õ[F!FðMøDà(ÛÝéBÝ#\à0 ZFGñ##Ñ. ZFGmºñªñ
ÝÜàøZFGm¸ñ¨ñôÜ[F!F«æ-+ -éðAF%FFÔà9F °GmdùÕ(F½èð-éðAF%FFÈÕ0’à ‘ÕàAF8F°GmdùÕ(F½èðJh*Ð
hSpHh#HpGðµF°F2¡ü÷Èø(¿%0OÐWø%H±m-ùÓGà-IhB
`°ð½-?Ò x:(Ð!FhFþ÷ýhFþ÷mý(3ÐhFþ÷mý(hF Ðþ÷Uý#àjF¡ Fü÷Åøàþ÷?ý³ð¿$пð¿Dôtð¿DôdFhFþ÷UýF0h”Fh0FG(¿Gø%è°ð½Oðÿ0°ð½ð¿$ÛÑð¿ $$Õç:ttl :%p(¼¿ pGJëPø.......
here is a corrected code that cleanly compiles, and works as desired
Note the way the printf() parameters are being set
Note the corrected list of #include statements
//include "mbed.h"
#include <stdio.h> // printf()
#include <string.h> // strstr()
#include <stdbool.h> // bool, true, false
char input[] = "Hello mbed";
char value[] = "llo";
int main( void )
{
char * output = strstr(input, value);
bool found = false;
if (output)
{
found = true;
}
printf( "%s\n", ((found)? "true" : "false" ));
}
There's a problem with the compiler and how it works with const strings. Add the NULL character to the strings to see if it stops printing...
printf(found ? "true\0" : "false\0");
printf() might be a macro on your compiler/library/IDE. Including the header file, ensures that it works as expected. Also, on embedded, main() should never return

I can not overflow buffer

I have seen a buffer overflow code but I can not over flow it. Is there any gcc option to compile that? Or any wrong with that code.
The code is:
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
int main(int argc, char **argv)
{
volatile int modified;
char buffer[64];
if(argc == 1) {
errx(1, "please specify an argument\n");
}
modified = 0;
strcpy(buffer, argv[1]);
if(modified == 0x61626364) {
printf("you have correctly got the variable to the right value\n");
} else {
printf("Try again, you got 0x%08x\n", modified);
}
}
and I am trying to run it this way:
perl -e 'print "A"x64 . "dcba"' | xargs ./main
You need to know
Know the stack memory layout and the address difference between the variable modified and buffer
You can solve it by finding the offset between modified and buffer as (char *)&modified - (char *)buffer
Your machine endianess. I have used the stack overflow answer for this purpose
The linked demonstrates how to run the modified code that serves the purpose of determining the correct argument as well as stack smashing. The first Demo provides you with the argument that you can feed to your second Demo

Display an int variable in a MessageBox

I am working on an old app written in Visual C++ 6.0. I am trying to display an int variable in a MessageBox for debugging reasons. Here is my code, I thought this would be a simple process, but I am just learning C++. The two lines that are commented I have tried as well with similar errors. Below is the error I am getting.
int index1 = 1;
char test1 = index1;
// char var1[] = index1;
// char *varGo1 = index1;
MessageBox(NULL, test1, "testx", MB_OK);
error C2664: 'MessageBoxA' : cannot convert parameter 2 from 'char' to 'const char *'
Why bother with C-style strings if you tagged C++?
Although Mark Ransom provided MFC solution (which is perfectly valid), here is a Standard C++ one:
int index1 = 1;
std::string test1 = std::to_string(index1);
MessageBoxA(NULL, test1.c_str(), "testx", MB_OK);
References:
std::to_string();
Arrays are evil
Use boost::format for more sophisticated formatting.
int index1 = 1;
char buf[10];
itoa(index1,buf,10);
MessageBox(NULL,buf,"Caption",MB_OK);
Can try this
CString str1;
str1.Format(_T("%d"), index1);
MessageBox(NULL, str1, "testx", MB_OK);
CString's Format works just like printf to populate the string with the parameter list.
The second parameter of MessageBox needs to be a pointer to a string of chars, terminated with NULL. Passing a char will not work.
But, learning to use a debugger is an integral part to learning a language. Why not build a debug build and set a breakpoint on char test1 = index1; instead? You do that by pressing F9 when the cursor is on that line.
For what it's worth, I prefer to use a manipulator for this:
#include <sstream>
#include <iostream>
#include <windows.h>
using std::ostringstream;
using std::ostream;
ostream &msg_box(ostream &s) {
ostringstream &os = dynamic_cast<ostringstream &>(s);
MessageBox(NULL, os.str().c_str(), "testx", MB_OK);
return s;
}
int main() {
ostringstream msg;
msg << "The number is: " << 10 << msg_box;
return 0;
}
This maintains (mostly) the same interface nearly everybody's already accustomed to with iostreams, avoids the type-unsafe CString::Format, and avoids having several lines of distraction everywhere you're going to display a little information for debugging. The other obvious good point is that if you've overloaded operator<< for your own type, that overload will work with this as well.
Acording to your error, you should declare a const pointer on the second parameter.
Like this,
const char * test1= new char();
or use
std::string test1= "";
MessageBox(NULL, test1.c_str(), "testx", MB_OK);
Also using just "Text" will work.
Here is the pure C solution using sprintf method to store all input in buffer and passing that buffer to MessageBox.
#include <stdio.h>
#include <windows.h>
int main(void)
{
int intVal = 50;
float fltVal = 5.5;
char *str = "Test String";
char buf[1024] = {'\0'};//buffer to store formatted input.
//convert formatted input into buffer.
sprintf(buf,"Int value : %d\nFloat value : %f\nString : %s\n",intVal,fltVal,str);
//display whole buffer.
MessageBox(NULL,buf,"INFO",MB_ICONINFORMATION);
return 0;
}

Basics of strtol?

I am really confused. I have to be missing something rather simple but nothing I am reading about strtol() is making sense. Can someone spell it out for me in a really basic way, as well as give an example for how I might get something like the following to work?
string input = getUserInput;
int numberinput = strtol(input,?,?);
The first argument is the string. It has to be passed in as a C string, so if you have a std::string use .c_str() first.
The second argument is optional, and specifies a char * to store a pointer to the character after the end of the number. This is useful when converting a string containing several integers, but if you don't need it, just set this argument to NULL.
The third argument is the radix (base) to convert. strtol can do anything from binary (base 2) to base 36. If you want strtol to pick the base automatically based on prefix, pass in 0.
So, the simplest usage would be
long l = strtol(input.c_str(), NULL, 0);
If you know you are getting decimal numbers:
long l = strtol(input.c_str(), NULL, 10);
strtol returns 0 if there are no convertible characters at the start of the string. If you want to check if strtol succeeded, use the middle argument:
const char *s = input.c_str();
char *t;
long l = strtol(s, &t, 10);
if(s == t) {
/* strtol failed */
}
If you're using C++11, use stol instead:
long l = stol(input);
Alternately, you can just use a stringstream, which has the advantage of being able to read many items with ease just like cin:
stringstream ss(input);
long l;
ss >> l;
Suppose you're given a string char const * str. Now convert it like this:
#include <cstdlib>
#include <cerrno>
char * e;
errno = 0;
long n = std::strtol(str, &e, 0);
The last argument 0 determines the number base you want to apply; 0 means "auto-detect". Other sensible values are 8, 10 or 16.
Next you need to inspect the end pointer e. This points to the character after the consumed input. Thus if all input was consumed, it points to the null-terminator.
if (*e != '\0') { /* error, die */ }
It's also possible to allow for partial input consumption using e, but that's the sort of stuff that you'll understand when you actually need it.
Lastly, you should check for errors, which can essentially only be overflow errors if the input doesn't fit into the destination type:
if (errno != 0) { /* error, die */ }
In C++, it might be preferable to use std::stol, though you don't get to pick the number base in this case:
#include <string>
try { long n = std::stol(str); }
catch (std::invalid_argument const & e) { /* error */ }
catch (std::out_of_range const & e) { /* error */ }
Quote from C++ reference:
long int strtol ( const char * str, char ** endptr, int base );
Convert string to long integer
Parses the C string str interpreting its content as an integral number of the specified base, which is returned as a long int value. If endptr is not a null pointer, the function also sets the value of endptr to point to the first character after the number.
So try something like
long l = strtol(pointerToStartOfString, NULL, 0)
I always use simply strol(str,0,0) - it returns long value. 0 for radix (last parameter) means to auto-detect it from input string, so both 0x10 as hex and 10 as decimal could be used in input string.

Remove leading % from integer

Just a simple problem here: I have a char** argv[] that holds all of my arguments...in one of these arguments, I get an integer proceeded by a %
For example:
bg %2
I really just want the integer....is there an easy way to get this?
This is for homework, so I am willing to do some more digging if anyone can prod me in the right direction.
Thanks
Here is a way to do it using c++ methods:
lets assume you have one of the char* in the list char** argv[]
std::string tempString(argv[the one with the %]);
int position = tempString.find_first_of('%');
int = atoi(tempString.substr(position, tempString.size()-position).c_str());
A quick explination, the first line converst the char* into a std::string, the second line gets the position of the %, the third line gets the sub-string of the number (assuming it ends at the end of the char*), converts it back to a char* and passes it through atoi to get the int.
Hope this helps.
Here is one way to do it using atoi:
for (int i = 0 ; i != argc ; i++) {
if (argv[i][0] == '%') {
int num = atoi(&argv[i][1]);
printf("Got a number: %d\n", num);
}
}