I am counting approximation of Pi, I have made it to 3,14596, but I have tried to set integral for counting pi as a parameter when starting program and no result came from it. I tried add when starting program 4/1+x*x (there should by brackets around 1+x*x, but compilator sees them as a mistake), and I get it from args[1] as a 4 only when I transfered char to int with itoa(). Is there any way how to pass it to application for computing? This is the line in my program:
float sum, integral;
integral=4/(1+x*x);
sum=sum+integral;
And I have it in for loop. In this case it counts great, but how to incorporate theese parameter?I have thought of some specific char replacement (I would replace X for an actual value), but is it possible?
You can't pass the formula as argument of your program. Your arg[1] parameter is a string, when you call atoi you make only the conversion of the numbers up to the first nun numeric character, so in your case it converted the '4' character of your string "4/1+x*x" and stopped conversion at the '/'.
If you want to use the formula, you have to write an interpreter that analyzes the string, builds an evaluation tree and execute by replacing the values of the variables. Something quite complicated, probably not under several hundred lines of code.
It's probably easier to use the formula in the source code and recompile the program accordingly. If it's not possible, change to an interpreted language like perl, python, javascript which implement the eval function.
Related
I was asked to write a program that operates on a given string. The commands come in the form of two letters followed by nothing, or an int(s) or string(s). The commands work on the given string (reversing it, multiplying it, replacing instances of a substring with another substring).
I'm pretty new to C and programming in general, and I have difficulty in recieving the commands themselves. How do I both make sure that the command I'm given is correct in both name and arguments? Will I need to use an array of functions (does that exist?) after I've found that the command I was given was correct?
I'd recommend that you learn how to use sscanf, which sounds perfect for what you want.
If the string is stored in the array a, you can use something like this to see if the two letters are "IA" followed by an int:
sscanf(a, "IA %d", &intVar);
If you want to check for the case of the letters "SA" followed by a string:
sscanf(a, "SA %s", &charArray);
The key here is checking the return value of sscanf, so you can know how many of the arguments were successfully assigned values from the format string. This means you can also add arguments for more strings, assuming that there's some maximum number of ints / strings that could follow the two letters.
I am trying to save the data type given as a command line argument in my C program and use that type in the whole program without checking it. For example, I could run the program "./name -d int" or "./name -d float" and I want the data type to be saved for further use and to be seen in the entire program, not only in the main() function. A short example:
int main() {
/* read command line argument */
/* I would like to be able to save the type in T to use like this */
T a[20];
/* rest of the program */
}
Could I do this?
Thank you.
As pointed out by an earlier answer, you can't do this in c unless you have something like switch statements in your code that handle different cases, because data types are determined at compile time. If you are willing to settle for less than 64 bit precision for integers and you have 64 bit doubles, you can use doubles for all of your numbers and then just have switch statements e.g. when you output, that convert the double to an integer or char etc. as necessary and then output in the desired format.
No you can't do that in C.
Types have to be determined are compile-time, you can't choose the type at runtime.
More dynamic languages (like Objective-C for instance) will allow you to do such things.
Why are you trying to do that in the first place ? Maybe we can provide any more guidance.
I am just learning C and in my class this is a part of our first program.
The full description of the function I am trying to implement:
if that's tl;dr, a key point is that I am not allowed to use functions from other libraries (so something like srtol is ruled out).
int parseHexString(char *hexString, int *integerRead); The first
parameter is a null terminated C string, that represents a hexadecimal
integer. This function parses this string, accumulating the integer
value it represents. This integer value is placed at the location
pointed to by the second parameter, integerRead. If a bad hexadecimal
character, thus an invalid hex value, is encountered, this function
stops looking at further characters within the string and returns -1.
If a good hex value is parsed, it returns 0.
The correct way to implement this function looks at the first
character within the string first and does not use a stack to
accomplish the parsing. Your first assembly language program will need
to implement what this function accomplishes, so you will save
yourself time by implementing this function the correct way.
For this function, do not call any functions from any libraries; as an
exception, for debugging purposes only, you may use printf(). It will
help our grading if you remove your debugging code before you submit
your assignment.
I am NOT just looking for a full implementation of this function, just some tips or hints to get me started.
I feel as though there is some intuitive way of doing this, but right now I am blanking. I'm concerned with how I am supposed to start at the first character of the string and then go forward from there to convert it to decimal.
How about:
Get the length of the string
Walk the string from left to right
For each character:
Check if it's a valid hex character
Add its decimal value multiplied by 16^x, where x is the number of characters left on the right
please take a look at the two following c statements
printf("a very long string");
printf("%s","a very long string");
they produce the same result,but there is definitely some difference under the hood,so what is the difference and which one is better? Please share your ideas!
If you know what the string contents are, you should use the first form because it is more compact. If the string you want to print can come from the user or from any other source such that you do not know what the string contents are, you must use the second form; otherwise, your code will be wide open to format string injection attacks.
The first printf works like this
'a' is not a special character: print it
' ' is not a special character: print it
'v' is not a special character: print it
...
'g' is not a special character: print it
The second printf works like this
'%' is a special character:
's' print the contents of the string pointed to by the 2nd parameter
The first one passes one parameter and the second passes 2, so the call is slightly faster in the first one.
But in the first one, printf() has to scan the long string for format specifications and in the second one, the format string is very short, so the actual processing is probably faster in the second one.
More important (to me anyway), is that "a very long string" is not likely to be a a constant string as it is in this example. If you're printf'ing a long string, you're probably using a pointer to to something that the program generated. In that case, it's a MUCH better idea to use the second form because otherwise somewhere, somehow, sometime, the long string will contain a format printf format specification and that will cause printf to go looking for another argument and your program will crash. This exact problem just happened to me about a week ago in code that we have been using for nearly 20 years.
The bottom line is that your printf format specification should always be a constant string. If you need to output a variable, use printf("%s",var) or better yet, fputs(var, stdout).
The first is no less efficient than the second. Since there are no format sequences and no corresponding arguments, no work must be done by the printf() function. In the second case, if the compiler isn't smart enough to catch this, you will be calling for unnecessary work (note: miniscule compared to actually sending (and reading!) the output at the terminal.
printf was designed for printing with formatting. It is more useful to provide formatting arguments for the sake of debugging although they aren't required.
%s takes a value of a const char* whereas leaving no argument just prints the literal expression.
You could still cast a different pointer to the const char* explicitly and change its contents without changing the output expression.
First of all you should define "better" better since it is not smart enough by itself. Better in what way? performance, maintenance, readibility, extensibilty ...
With the one line of code presented I would choose option 1 for almost all versions of 'better'
It's more readible
It does what it should do and nothing more (KISS principle)
It's faster (no pointless moving memory around to stuff one string into another). But unless you are doing this printf a hell of a lot of times in a loop this is not that a big plus.
(in c90) (linux)
input:
sqrt(2 - sin(3*A/B)^2.5) + 0.5*(C*~(D) + 3.11 +B)
a
b /*there are values for a,b,c,d */
c
d
input:
cos(2 - asin(3*A/B)^2.5) +cos(0.5*(C*~(D)) + 3.11 +B)
a
b /*there are values for a,b,c,d */
c
d
input:
sqrt(2 - sin(3*A/B)^2.5)/(0.5*(C*~(D)) + sin(3.11) +ln(B))
/*max lenght of formula is 250 characters*/
a
b /*there are values for a,b,c,d */
c /*each variable with set of floating numbers*/
d
As you can see infix formula in the input depends on user.
My program will take a formula and n-tuples value.
Then it calculate the results for each value of a,b,c and d.
If you wonder I am saying ;outcome of program is graph.
/sometimes,I think i will take input and store in string.
then another idea is arise " I should store formula in the struct"
but ı don't know how I can construct
the code on the base of structure./
really, I don't know way how to store the formula in program code so that
I can do my job.
can you show me?
/* a,b,c,d is letters
cos,sin,sqrt,ln is function*/
You need to write a lexical analyzer to tokenize the input (break it into its component parts--operators, punctuators, identifiers, etc.). Inevitably, you'll end up with some sequence of tokens.
After that, there are a number of ways to evaluate the input. One of the easiest ways to do this is to convert the expression to postfix using the shunting yard algorithm (evaluation of a postfix expression is Easy with a capital E).
You should look up "abstract syntax trees" and "expression trees" as well as "lexical analysis", "syntax", "parse", and "compiler theory". Reading text input and getting meaning from it is quite difficult for most things (though we often try to make sure we have simple input).
The first step in generating a parser is to write down the grammar for your input language. In this case your input language is some Mathematical expressions, so you would do something like:
expr => <function_identifier> ( stmt )
( stmt )
<variable_identifier>
<numerical_constant>
stmt => expr <operator> stmt
(I haven't written a grammar like this {look up BNF and EBNF} in a few years so I've probably made some glaring errors that someone else will kindly point out)
This can get a lot more complicated depending on how you handle operator precedence (multiply and device before add and subtract type stuff), but the point of the grammar in this case is to help you to write a parser.
There are tools that will help you do this (yacc, bison, antlr, and others) but you can do it by hand as well. There are many many ways to go about doing this, but they all have one thing in common -- a stack. Processing a language such as this requires something called a push down automaton, which is just a fancy way of saying something that can make decisions based on new input, a current state, and the top item of the stack. The decisions that it can make include pushing, popping, changing state, and combining (turning 2+3 into 5 is a form of combining). Combining is usually referred to as a production because it produces a result.
Of the various common types of parsers you will almost certainly start out with a recursive decent parser. They are usually written directly in a general purpose programming language, such as C. This type of parser is made up of several (often many) functions that call each other, and they end up using the system stack as the push down automaton stack.
Another thing you will need to do is to write down the different types of words and operators that make up your language. These words and operators are called lexemes and represent the tokens of your language. I represented these tokens in the grammar <like_this>, except for the parenthesis which represented themselves.
You will most likely want to describe your lexemes with a set of regular expressions. You should be familiar with these if you use grep, sed, awk, or perl. They are a way of describing what is known as a regular language which can be processed by something known as a Finite State Automaton. That is just a fancy way of saying that it is a program that can make a decision about changing state by considering only its current state and the next input (the next character of input). For example part of your lexical description might be:
[A-Z] variable-identifier
sqrt function-identifier
log function-identifier
[0-9]+ unsigned-literal
+ operator
- operator
There are also tools which can generate code for this. lex which is one of these is highly integrated with the parser generating program yacc, but since you are trying to learn you can also write your own tokenizer/lexical analysis code in C.
After you have done all of this (it will probably take you quite a while) you will need to have your parser build a tree to represent the expressions and grammar of the input. In the simple case of expression evaluation (like writing a simple command line calculator program) you could have your parser evaluate the formula as it processed the input, but for your case, as I understand it, you will need to make a tree (or Reverse Polish representation, but trees are easier in my opinion).
Then after you have read the values for the variables you can traverse the tree and calculate an actual number.
Possibly the easiest thing to do is use an embedded language like Lua or Python, for both of which the interpreter is written in C. Unfortunately, if you go the Lua route you'll have to convert the binary operations to function calls, in which case it's likely easier to use Python. So I'll go down that path.
If you just want to output the result to the console this is really easy and you won't even have to delve too deep in Python embedding. Since, then you only have to write a single line program in Python to output the value.
Here is the Python code you could use:
exec "import math;A=<vala>;B=<valb>;C=<valc>;D=<vald>;print <formula>".replace("^", "**").replace("log","math.log").replace("ln", "math.log").replace("sin","math.sin").replace("sqrt", "math.sqrt").replace("cos","math.cos")
Note the replaces are done in Python, since I'm quite sure it's easier to do this in Python and not C. Also note, that if you want to use xor('^') you'll have to remove .replace("^","**") and use ** for powering.
I don't know enough C to be able to tell you how to generate this string in C, but after you have, you can use the following program to run it:
#include <Python.h>
int main(int argc, char* argv[])
{
char* progstr = "...";
Py_Initialize();
PyRun_SimpleString(progstr);
Py_Finalize();
return 0;
}
You can look up more information about embedding Python in C here: Python Extension and Embedding Documentation
If you need to use the result of the calculation in your program there are ways to read this value from Python, but you'll have to read up on them yourself.
Also, you should review your posts to SO and other posts regarding Binary Trees. Implement this using a tree structure. Traverse as infix to evaluate. There have been some excellent answers to tree questions.
If you need to store this (for persistance as in a file), I suggest XML. Parsing XML should make you really appreciate how easy your assignment is.
Check out this post:
http://blog.barvinograd.com/2011/03/online-function-grapher-formula-parser-part-2/
It uses ANTLR library for parsing math expression, this one specifically uses JavaScript output but ANTLR has many outputs such as Java, Ruby, C++, C# and you should be able to use the grammar in the post for any output language.