Convert string to short in C++ - c++

So I've looked around for how to convert a string to a short and found a lot on how to convert a string to an integer. I would leave a question as a comment on those threads, but I don't have enough reputation. So, what I want to do is convert a string to a short, because the number should never go above three or below zero and shorts save memory (as far as I'm aware).
To be clear, I'm not referring to ASCII codes.
Another thing I want to be able to do is to check if the conversion of the string to the short fails, because I'll be using a string which consists of a users input.
I know I can do this with a while loop, but if there's a built in function to do this in C++ that would be just as, or more, efficient than a while loop, I would love to hear about it.

Basically, an std::stos function is missing for unknown reasons, but you can easily roll your own. Use std::stoi to convert to int, check value against short boundaries given by e.g. std::numeric_limits<short>, throw std::range_error if it's not in range, otherwise return that value. There.
If you already have the Boost library installed you might use boost::lexical_cast for convenience, but otherwise I would avoid it (mainly for the verbosity and library dependency, and it's also a little inefficient).
Earlier boost::lexical_cast was known for not being very efficient, I believe because it was based internally on stringstreams, but as reported in comments here the modern version is faster than conversion via stringstream, and for that matter than via scanf.

An efficient way is to use boost::lexical_cast:
short myShort = boost::lexical_cast<short>(myString);
You will need to install boost library and the following include: #include <boost/lexical_cast.hpp>
You should catch bad_lexical_cast in case the cast fails:
try
{
short myShort = boost::lexical_cast<short>(myString);
}
catch(bad_lexical_cast &)
{
// Do something
}

You can also use ssprintf with the %hi format specifier.
Example:
short port;
char szPort[] = "80";
sscanf(szPort, "%hi", &port);

the number should never go above three or below zero
If you really really need to save memory, then this will also fit in a char (regardless whether char is signed or unsigned).
Another 'extreme' trick: if you can trust there are no weird things like "002" then what you have is a single character string. If that is the case, and you really really need performance, try:
char result = (char)( *ptr_c_string - '0' );

Related

C++ regular expression

I need to capture data from a variable using a regular expression. The data are available on the form: Ip=8.8.8.8&probe=ip/tcp{dst=53}
for example.
To achieve this I`m using:
char *data;
data = getenv("QUERY_STRING");
char ipt[40];
char probe[40];
sscanf(data,"ip=%[0-9a-zA-Z-.]&probe=%[0-9a-zA-Z-.{}/=]",ipt,probe);
The second field will always contain a / but I can't get this and the other special carachters ({}=)
What can I do?
I already tried:
sscanf(data,"ip=%[0-9a-zA-Z-.]&probe=%[(...)]",ipt,probe);
And had no success as well.
Given that you know the probe part ends with } and the IP part end with a &, it's probably easiest to just scan for those:
sscanf(input, "Ip=%[^&]&probe=%[^}]", ipt, probe);
One minor detail: scanf with either a scanset or a %s conversion needs to have the buffer size specified to have any safety at all. without a length, both are pretty much equivalent to gets for lack of safety, so you really want something like:
char ipt[256], probe[256];
sscanf(input, "Ip=%255[^&]&probe=%255[^}]", ipt, probe);
Also note that this will give you the probe part without the trailing }. If you really need it, you can use something like strncat to add it back on afterwards though.
For those looking on: no, scanf (and company) don't support full regular expressions, but they do support scansets, which is what he's using here.

How to store a long hex value message in C++

I'm learning a crypto class and one of the assignment asked us to xor a bunch of hex ciphertext and try to find the encrypted message.
I know that you can do '0x' in front of int or long to hold a hex value in a variable, but what if my message is this long:
271946f9bbb2aeadec111841a81abc300ecaa01bd8069d5cc91005e9fe4aad6e04d513e96d99de2569bc5e50eeeca709b50a8a987f4264edb6896fb537d0a716132ddc938fb0f836480e06ed0fcd6e9759f40462f9cf57f4564186a2c1778f1543efa270bda5e933421cbe88a4a52222190f471e9bd15f652b653b7071aec59a2705081ffe72651d08f822c9ed6d76e48b63ab15d0208573a7eef027
I would get an overflow. Is there a way to put the whole message into one variable? I could split the message into subparts, but I prefer it to be in variable instead of many (if that is possible). I tried to use string to hold the massage, but how can I use the operator, '^', for xor?
Or is there a more simple technique that I do not know of?
Thanks
For something like this, you'd typically use a string or a vector<char> to hold the data. You can't use the entire string/vector as an operand to ^, but you can apply it one byte at a time.
If you want to simplify the rest of the code, you could create a class that overloaded operator^ to do a byte-wise XOR, so your code would look something like result = key ^ message;.
You could use an array of, well, any size integer, and apply your operators to it an element at a time (which will probably be a bit more efficient than an array of characters). #JerryCoffin's idea of wrapping it inside a class w/ an overloaded operator is a good one, regardless of the actual representation you use.
Put it in a separate text file
read the file into a buffer
convert ascii chars to hex values
Jerry & Scott have sound suggestions. Another option is to use an existing library: for example, the GNU GMP arbitrary-precision maths library at http://gmplib.org, which supports XOR (see http://gmplib.org/manual/Integer-Logic-and-Bit-Fiddling.html#Integer-Logic-and-Bit-Fiddling) and a "scanf" style function to read in hex (see http://gmplib.org/manual/Formatted-Input-Strings.html#Formatted-Input-Strings), and explicitly aims to provide excellent support for cryptography.

When to use std::string vs char*? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
C++ char* vs std::string
I'm new to C++ coming from C# but I really do like C++ much better.
I have an abstract class that defines two constant strings (not static). And I wondered if a const char* would be a better choice. I'm still getting the hang of the C++ standards, but I just figured that there really isn't any reason why I would need to use std::string in this particular case (no appending or editing the string, just writing to the console via printf).
Should I stick to std::string in every case?
Should I stick to std::string in every case?
Yes.
Except perhaps for a few edge cases where you writing a high performance multi-threaded logging lib and you really need to know when a memory allocation is going to take place, or perhaps in fiddling with individual bits in a packet header in some low level protocol/driver.
The problem is that you start with a simple char and then you need to print it, so you use printf(), then perhaps a sprintf() to parse it because std::stream would be a pain for just one int to string. And you end up with an unsafe and unmaintainable mix oc c/c++
I would stick to using std::string instead of const char*, simply because most of the built-in C++ libraries work with strings and not character arrays. std::string has a lot of built-in methods and facilities that give the programmer a lot of power when manipulating strings.
Should I stick to std::string in every case?
There are cases where std::string isn't needed and just a plain char const* will do. However you do get other functionality besides manipulation, you also get to do comparison with other strings and char arrays, and all the standard algorithms to operate on them.
I would say go with std::string by default (for members and variables), and then only change if you happen to see that is the cause of a performance drop (which it won't).
Use std::string when you need to store a value.
Use const char * when you want maximum flexibility, as almost everything can be easily converted to or from one.
This like comparing Apples to Oranges. std::string is a container class while char* is just a pointer to a character sequence.
It really all depends on what you want to do with the string.
Std::string on the other hand can give you a quick access for simple string calculation and manipulation function. Most of those are simple string manipulation functions, nothing fancy really.
So it basically depends on your needs and how your functions are declared. The only advantage for std::string over a char pointer is that it doesnt require a specific lenghth decleration.

C++: Is it safe to move a jpeg around in memory using a std::string?

I have an external_jpeg_func() that takes jpeg data in a char array to do stuff with it. I am unable to modify this function. In order to provide it the char array, I do something like the following:
//what the funcs take as inputs
std::string my_get_jpeg();
void external_jpeg_func(const char* buf, unsigned int size);
int main ()
{
std::string myString = my_get_jpeg();
external_jpeg_func(myString.data(), myString.length() );
}
My question is: Is it safe to use a string to transport the char array around? Does jpeg (or perhaps any binary file format) be at risk of running into characters like '\0' and cause data loss?
My recommendation would be to use std::vector<char>, instead of std::string, in this case; the danger with std::string is that it provides a c_str() function and most developers assume that the contents of a std::string are NUL-terminated, even though std::string provides a size() function that can return a different value than what you would get by stopping at NUL. That said, as long as you are careful to always use the constructor that takes a size parameter, and you are careful not to pass the .c_str() to anything, then there is no problem with using a string here.
While there is no technical advantage to using a std::vector<char> over a std::string, I feel that it does a better job of communicating to other developers that the content is to be interpreted as an arbitrary byte sequence rather than NUL-terminated textual content. Therefore, I would choose the former for this added readability. That said, I have worked with plenty of code that uses std::string for storing arbitrary bytes. In fact, the C++ proto compiler generates such code (though, I should add, that I don't think this was a good choice for the readability reasons that I mentioned).
std::string does not treat null characters specially, unless you don't give it an explicit string length. So your code will work fine.
Although, in C++03, strings are technically not required to be stored in contiguous memory. Just about every std::string implementation you will find will in fact store them that way, but it is not technically required. C++11 rectifies this.
So, I would suggest you use a std::vector<char> in this case. std::string doesn't buy you anything over a std::vector<char>, and it's more explicit that this is an array of characters and not a possibly printable string.
I think it is better to use char array char[] or std::vector<char>. This is standard way to keep images. Of course, binary file may contain 0 characters.

how to do trig functions to data in Windows textboxes

must you convert from strings to double? if so. how?
Are there functions for trig that will accept textbox string data as is?
Is there a way to pull the data from the textbox as a numeric value, not as a string?
must you convert from strings to double? if so. how?
Yes. There are quite a few ways to do this.
Are there functions for trig that will accept textbox string data as is?
No, but if you really wanted one, you could easily implement such a function using one of the techniques described in the aforementioned question.
Usually you want to validate user input to be sure it is correct before you use it, and validation of the input in numeric form is much easier than validation of the raw string.
Is there a way to pull the data from the textbox as a numeric value, not as a string?
Maybe; it depends entirely on what GUI framework you are using.
must you convert from strings to double?
Yes.
if so. how?
The C++ way is to use the string streams; in particular, you'll probably want to use istringstream. A viable alternative is to follow the C way, i.e. use sscanf with the appropriate format specifier ("%f").
Another C++ option is to use the boost lexical_cast, but starting to use boost just for lexical_cast is a bit overkill in my opinion.
Example with istringstream:
#include <sstream>
// ...
std::istringstream strParser(yourString);
double yourDouble;
strParser>>yourDouble;
if(strParser.fail())
{
// the string couldn't be converted to a double
}
else if(!strParser.eof())
{
// the string hasn't been fully consumed; this may or may not be a problem, depending on your needs
}
Are there functions for trig that will accept textbox string data as is?
AFAIK no, there's no need of them (although you can write them quite easily).
Is there a way to pull the data from the textbox as a numeric value, not as a string?
The WinAPIs provide a handful of such "convenience functions" for use in dialogs, but the only one I can recall that provides such help is GetDlgItemInt, which, as the name may suggest, works only for integers.
Addendum
I see now that you are using C++/CLI (you mentioned System::String): well, you should have said that, this changes the options quite a bit.
In the managed world, your best option is to use the Double::Parse method; to catch bad-formatted strings, you should either catch the exceptions thrown by Double::Parse or call Double::TryParse before calling Double::Parse.
Addendum bis
Uh, I forgot, since you're using the .NET Framework probably it should be better to use the .NET trigonometric functions (class System.Math).
I'd recommend using strtod
char *str = ...;
const char *end;
double d = strtod(str, &end);
if (*end != '\0')
{
// questionable data
}
There's no way to do a straight conversion from textbox to double as far as I know. You'll need to first convert to a double with something like strtod.
You could easily make a generic function which accepts a textbox control as an argument and returns a double (assuming it's the textbox contains a valid number) mind you..