C: How to filter commands? - c

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.

Related

How to wildcard search with capture in C?

I'm trying to write a routine in C to capture sequences of characters in a string argument. The matching criteria in addition to characters can have ? meaning exactly one character and * meaning zero or more characters. (lazy).
e.g.
string: ok1ok1234567890
match: *(ok?2*)4*
The result should be the position of the match = 3 and the length of the match = 5
I have tried numerous ways of doing this, have put it aside, come back to it, put it aside again etc. I cannot crack it. It needs to be a purely C solution and able to capture multiple captures.
e.g. (*)(ok??)3(4*)8*
Every solution I come up with works in many cases but not all. I'm hoping someone somewhere might have done this already or have an insight to how it can be done.

How can I parse text input and convert strings to integers?

I have a file input, in which i have the following data.
1 1Apple 2Orange 10Kiwi
2 30Apple 4Orange 1Kiwi
and so on. I have to read this data from file and work on it but i dont know how to retrieve the data. I want to store 1(of 1 apple) as integer and then Apple as a string.
I thought of reading the whole 1Apple as a string. and then doing something with the stoi function.
Or I could read the whole thing character by character and then if the ascii value of that character lies b/w 48 to 57 then i will combine that as an integer and save the rest as string? Which one shall I do? Also how do I check what is the ASCII value of the char. (shall I convert the char to int and then compare, or is there any inbuilt function?)
How about using the fscanf() function if and only if your input pattern is not going to change. Otherwise you should probably use fgets() and perform checks if you want to separate the number from the string such as you suggested.
There is one easy right way to do this with standard C library facilities, one rather more difficult right way, and a whole lot of wrong ways. This is the easy right way:
Read an entire line into a char[] buffer using fgets.
Extract numbers from this line using strtol or strtoul.
It is very important to understand why the easier-looking alternatives (*scanf and atoi) should never be used. You might write less code initially, but once you start thinking about how to handle even slightly malformed input, you will discover that you should have used strtol.
The "rather more difficult right way" is to use lex and yacc. They are much more complicated but also much more powerful. You shouldn't need them for this problem.

Comparison between the two printf statements

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.

C - explicit integral as a parameter

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.

When would you use strings instead of characters?

When is it appropriate to use strings instead of characters? What about vice-versa?
Strings and characters represent fundamentally different concepts.
A character is a single, indivisible unit representing some sort of glyph. When working with a character, you are guaranteed to have a single character, no more or no less. Functions that work with characters are best suited for cases where you know this to be true. For example, if you were writing "Hangman" and wanted to process a user's guess, it would make sense for the function that processes the guess to take a character rather than a string, since you know for a fact that the input to that function should always be a single letter.
A string is a composite type formed by taking zero or more characters and putting them together. Strings are typically used to represent text, which can have an arbitrary length, including having zero length. Functions that work on strings are best suited for cases where the input is known to be made of letters, but it's unclear how many letters there are going to be.
One other option is to use a fixed-length array of characters, which is ideal for the situation where you know that you have exactly k characters for some k. This does not come up very much, but it's another option.
In short, use characters when you know that you need to work on a piece of text that is just one glyph long. Use strings when you don't know the length of the input in advance. Use fixed-sized arrays when you know for a fact that the input has some particular length.

Resources