how to do trig functions to data in Windows textboxes - c++

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..

Related

Convert string to short in 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' );

scanf on an istream object

NOTE: I've seen the post What is the cin analougus of scanf formatted input? before asking the question and the post doesn't solve my problem here. The post seeks for C++-way to do it, but as I mentioned already, it is inconvenient to just use C++-way to do it sometimes and I have clear examples for that.
I am trying to read data from an istream object, and sometimes it is inconvenient to just use C++-style ways such as operator>>, e.g. the data are in special form 123:456 so you have to imbue to make ':' as space (which is very hacky, as opposed to %d:%d in scanf), or 00123 where you want to read as string and convert decimal instead of octal (as opposed to %d in scanf), and possibly many other cases.
The reason I chose istream as interface is because it can be derived and therefore more flexible. For example, we can create in-memory streams, or some customized streams that generated on the fly, etc. C-style FILE*, on the other hand, is very limited, at least in a standard-compliant way, on creating customized streams.
So my questions is, is there a way to do scanf-like data extraction on istream object? I think fscanf internally read character by character from FILE* using fgetc, while istream also provides such interface. So it is possible by just copying and pasting the code of fscanf and replace the FILE* with the istream object, but that's very hacky. Is there a smarter and cleaner way, or is there some existing work on this?
Thanks.
You should never, under any circumstances, use scanf or its relatives for anything, for three reasons:
Many format strings, including for instance all the simple uses of %s, are just as dangerous as gets.
It is almost impossible to recover from malformed input, because scanf does not tell you how far in characters into the input it got when it hit something unexpected.
Numeric overflow triggers undefined behavior: yes, that means scanf is allowed to crash the entire program if a numeric field in the input has too many digits.
Prior to C++11, the C++ specification defined istream formatted input of numbers in terms of scanf, which means that last objection is very likely to apply to them as well! (In C++11 the specification is changed to use strto* instead and to do something predictable if that detects overflow.)
What you should do instead is: read entire lines of input into std::string objects with getline, hand-code logic to split them up into fields (I don't remember off the top of my head what the C++-string equivalent of strsep is, but I'm sure it exists) and then convert numeric strings to machine numbers with the strtol/strtod family of functions.
I cannot emphasize this enough: THE ONLY 100% RELIABLE WAY TO CONVERT STRINGS TO NUMBERS IN C OR C++, unless you are lucky enough to have a C++ runtime that is already C++11-conformant in this regard, IS WITH THE strto* FUNCTIONS, and you must use them correctly:
errno = 0;
result = strtoX(s, &ends, 10); // omit 10 for floats
if (s == ends || *ends || errno)
parse_error();
(The OpenBSD manpages, linked above, explain why you have to do this fairly convoluted thing.)
(If you're clever, you can use ends and some manual logic to skip that colon, instead of strsep.)
I do not recommend you to mix C++ input output and C input output. No that they are really incompatible but they could just plain interoperate wrong.
For example Oracle docs recommend not to mix it http://www.oracle.com/technetwork/articles/servers-storage-dev/mixingcandcpluspluscode-305840.html
But no one stops you from reading data into the buffer and parsing it with standard c functions like sscanf.
...
string curString;
int a, b;
...
std::getline(inputStream, curString);
int sscanfResult == sscanf(curString.cstr(), "%d:%d", &a, &b);
if (2 != sscanfResult)
throw "error";
...
But it won't help in some situations when your stream is just one long contiguous sequence of symbols(like some string turned into memory stream).
Making your own fscanf from scratch or porting(?) the original CRT function actually isn't the worst possible idea. Just make sure you have tested it thoroughly(low level custom char manipulation was always a source of pain in C).
I've never really tried the boost\spirit and such parsing infrastructure could really be an overkill for your project. But boost libraries are usually well tested and designed. You could at least try to use it.
Based on #tmyklebu's comment, I implemented streamScanf which wraps istream as FILE* via fopencookie: https://github.com/likan999/codejam/blob/master/Common/StreamScanf.cpp

Recognize a specific string from a string array without iteration

I'm writing a derivative calculator in C++, and in order to properly perform the derivation operations, I need to parse the input equation at various character indexes along the equation's string.
I'm using isdigit() to parse out the numerical values from the equation and then store them into a separate string array, however now I need to parse out the mathematical symbols from the equation to identify which operation I need to perform.
Is there any way I can modify (overwrite?) isdigit() to recognize custom values from a string array? I'd like to avoid iteration to make my code a little less cluttered, since I'm already going to be using plenty of loops for the rest of this program and I want my code to be easy to follow. Does overwriting and inheritance in C++ work similarly to inheritance in Java (with the exception of multiple inheritance/interfaces)?
Please refrain from posting solutions that are irrelevant to the scope of this question, IE; different approaches to deriving equations in C++, as I've used this approach for some fairly specific reasons.
Thanks
You can use the new powerful C++11 regular expressions library that does almost what ever parsing you want. This way, you'll avoid iterations and code cluttering.
You can just use strchr. (Not everyone will like the macros here, but they do make combining character classes easy.)
#define OPERATOR "+-*/"
#define DIGIT "0123456789"
// Is c an operator
if (strchr(OPERATOR, c)) {
// Yes it is
}
or:
// Is c an operator or a digit?
if (strchr(OPERATOR DIGIT, c)) {
// Yup
}
Overriding and Inheritance works more or less the same as in Java.
You need to define a function as virtual and redefine it in derived class.
I know the "Please refrain from posting...", but I've written a library that does function parsing and derivation.
It is available at https://github.com/B3rn475/MathParseKit
I hope you can find some tips there.

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++ Dynamically convert string to any basic type

In C++ I need to convert a string to any type at runtime where I do not know what type I might be getting in the string. I have heard there is a lexical_cast in boost that I can use, but what would be the most effective way to implement it?
I might get a bunch of string like this from a client: Date="25/08/2010", Someval="2", Blah="25.5".
Now I want to be able to convert these strings to their type, eg, the Somval is obviously an int, and the Date could be a boost::date or whatever. The point is, I don't know at this time in what order these would be given to me, so it's hard to write some code that will perform a bunch of casts.
I could use a bunch of if/else statements or a switch/case statements, however I'm thinking that there is possibly a better way to do this.
I'm not looking for something different to lexical_cast, I can totally use that, I am looking to see if someone knows a better way then doing this:
std::string str = "256";
int a = lexical_cast<int>(str);
//now check if the cast worked, if not, try another...
This is too much of a guessing game, and if I have 10 possible types, for any given string, it sounds a bit ineffective. Especially if it has to do 1000's of these at any given time.
Can anybody advice?
Alex Brown notes - the example string is a fragment of the XML data that comes from the client.
Use an XML parser to read XML data, it will do almost all of the legwork for you, and deal with the ordering issues. Then you simply need to ask the parser for the data you need for the calculation.
Details differ with different XML parsers - go find one, read the documentation. If you need more help, come back here with an XML parser question.
GMan is right, you can not cast an arbitrary string to for example a Date type if the underlaying data structure is different. You can, however, parse the content and instantiate a new object using the data in the string. std::atoi() parses a c-string to an int for example.
You need to parse the string, not cast it.
What you're describing is actually a parser. Even the trial-and-error approach using lexical_cast is really just a (crude) parser.
I suggest to clarify the format of the input string and then, if it's simple enough, write a Recursive descent parser by hand to parse the input string into whatever data structure is convenient for your need.
you could use a VARIANT type of struct (i.e. one of every possible results, and a "type" specifying which it was, and a big enum of types), and a ConvertStringToVariant() function.
This is too much of a guessing game,
and if I have 10 possible types, for
any given string
If you're concerned about this, you need a lexical analyzer, such as flex or Boost::Spirit.
It will still be a guessing game, but a more "informed" guessing one.