I have for example a string (mathematical equation in postfix notation) that looks like this: The numbers are 5.33,5.32,6.33,3.22
5.335.32*6.333.22++
I'm looking to make it into prefix notation but simply reversing the string won't work due to the fact it has to retain the value of the number.
I've thought of doing a normal character by character swap in a for loop, and when encountering a digit make that into a substring and place it on afterwards but I haven't gotten it to work properly and now I'm stuck.
My end-goal is to make a binary expression tree out of that, so if there's an easier way than doing this also please let me know.
A stack-based approach:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *postfix_to_prefix(const char *string) {
char operator, *stack[1024];
int s = 0, number, fraction;
const char *tokens = string;
while (1) {
if (sscanf(tokens, "%1d.%2d", &number, &fraction) == 2) {
stack[s] = malloc(sizeof("1.00"));
(void) sprintf(stack[s++], "%4.2f", number + (fraction / 100.0));
tokens += strlen("1.00");
} else if (sscanf(tokens, "%c", &operator) == 1) {
char *operand1 = stack[--s];
char *operand2 = stack[--s];
stack[s] = malloc(strlen(operand1) + strlen(operand1) + sizeof(operator) + sizeof('\0'));
(void) sprintf(stack[s++], "%c%s%s", operator, operand1, operand2);
free(operand1);
free(operand2);
tokens += sizeof(operator);
} else {
break;
}
}
return stack[--s];
}
int main() {
const char *string = "5.335.32*6.333.22++";
printf("%s\n", string);
char *inverted = postfix_to_prefix(string);
printf("%s\n", inverted);
free(inverted);
return 0;
}
OUTPUT
> ./a.out
5.335.32*6.333.22++
++3.226.33*5.325.33
>
This is a bare bones implementation with no real error checking nor other finishing touches. You'll want to check that non-communitive operations like subtraction and division come out with the operands in the correct order and reverse them if not.
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main(void) {
char exp[] = "5.335.32*6.333.22++";
size_t len = strlen(exp);
char temp[len];
char *p = temp;
for(int i = len-1; i >= 0; ){
if(isdigit(exp[i])){
memcpy(p, &exp[i-4+1], 4);//all number have a length of 4
p += 4;
i -= 4;
} else {
*p++ = exp[i--];//length of op is 1
}
}
memcpy(exp, temp, len);//Write back
puts(exp);//++3.226.33*5.325.33
return 0;
}
Related
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
void initRandom() {
srand(time(NULL));
}
int intUniformRnd(int a, int b){
return a + rand() % (b-a+1);
}
const char* animaisQuatro[] = {"gato", "urso","vaca"};
int main() {
char quatro[4] = {'*' , '*' , '*', '*'};
initRandom();
printf("%s\n", animaisQuatro[intUniformRnd(0,2)]);
for(int i=0;i<4;i++){
printf("%c", quatro[i]);
}
return 0;
}
I have this code that give me a random animal from the array const char* animaisQuatro[] = {"gato", "urso","vaca","lapa"}; from here
initRandom();
printf("%s\n", animaisQuatro[intUniformRnd(0,2)]);
and then I want to put that random animal in another array letter by letter but I don't know how
First I reduced your code to a minimal and reproducible example (something you should do whenever you ask a question):
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
void initRandom() {
srand(time(NULL));
}
int intUniformRnd(int a, int b){
return a + rand() % (b-a+1);
}
const char* animaisQuatro[] = {"gato", "urso","vaca"};
int main() {
char quatro[4] = {'*' , '*' , '*', '*'};
initRandom();
printf("%s\n", animaisQuatro[intUniformRnd(0,2)]);
for(int i=0;i<4;i++){
printf("%c", quatro[i]);
}
return 0;
}
Then you can proceed like this:
int main() {
char quatro[4] = {'*' , '*' , '*', '*'};
initRandom();
// Get the animal name from a random position
char* name = animaisQuatro[intUniformRnd(0, 2)];
// Iterate four times
for (int i = 0; i < 4; i++) {
// Assign each `name` index to its respective `quatro` position
quatro[i] = name[i];
}
printf("%s", quatro);
return 0;
}
Tip: you can avoiding hardcoding the 2 when calling intUniformRnd. Note that
printf("%d\n", (int) sizeof(animaisQuatro));
printf("%d\n", (int) sizeof(char*));
printf("%d\n", (int) sizeof(animaisQuatro) / sizeof(char*));
outputs
24
8
3
Therefore, you can do
int length = (int) sizeof(animaisQuatro) / sizeof(char*);
int pos = intUniformRnd(0, length - 1);
This way, if you want to add more elements to animaisQuatro, you don't need to change the value inside intUniformRnd.
I want to put that random animal in other array letter by letter
To copy a string to another character array, code could use
// Risky
strcpy(quatro, animaisQuatro[intUniformRnd(0,2)]);
That would overflow quatro[] if it is too small and leads to undefined behavior. (Bad)
A better way to copy and prevent buffer overflow and alert of a failure:
int len = snprintf(quatro, sizeof quatro, "%s", animaisQuatro[intUniformRnd(0,2)]);
if (len >= sizeof quatro) {
fprintf(stderr, "quatro too small.\n");
}
Since C99 and selectively afterword, code could use a variable length array to form a right-size quatro array.
const char *animal = animaisQuatro[intUniformRnd(0,2)];
size_t sz = strlen(animal) + 1;
char quatro[sz];
strcpy(quatro, animal);
Yet since intUniformRnd[] is constant, no need to copy the text, just copy the address to a pointer:
const char *quatro = animaisQuatro[intUniformRnd(0,2)];
The function char *my(char *s, int n) takes a string s and shifts the characters of s by n places, causing the characters to wrap around the string.
For example, given the string "This is my Apple!" , a shift of n = 2 will result in
String1: "Th"
String2: "is is my Apple!"
if n<0 it will shift in negative direction.
You can just use printf to split a string. If you want the result in a char *, you have to allocate some memory and use sprintf instead.
Here is a example using sprintfand memory allocation to return a char *.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *shift(char *string, int n)
{
int len = strlen(string);
char *shiftedString = malloc(len + 1);
n %= len; // in case you shift over string length
if (n < 0) n += len; // backward shift
sprintf(shiftedString, "%s%*.*s", string + n, n, n, string);
return shiftedString;
}
int main()
{
char *result = shift("This is my Apple!", 2);
printf("shifted string : %s\n", result);
free(result);
return 0;
}
the string is actually a char-array char[]
you could use the strlen function in combination with a for loop like so.
You can put that in a function thus creating your own function that would shift letters based on input N.
#include <stdio.h>
#include <string.h>
int main()
{
char string[] = "This is my Apple!";
//Initialize "n" before initializing the string variables.
int n = 2;
int len = strlen(string);
char string1[n];
char string2[len - n];
for(int i = 0;i<len;i++){
if(i<n){
string1[i]=string[i];
}else{
string2[i-n]=string[i];
}
}
printf("string = %s\n",string);
printf("string1 = %s\n",string1);
printf("string2 = %s\n",string2);
return 0;
}
I have a hex string in the form of "404C49474854" .
I am trying to extract the text string out of it with :
void textFromHexString(char *hex,char *result)
{
for(int k=1;k<strlen(hex);k+=2)
{
char temp[3]={0};
sprintf(temp,"%c%c",hex[k-1],hex[k]);
*result=char((int)strtol(temp, NULL, 16));
result++;
*result ='\0';
print(temp); //**** edit
}
}
I call it from inside another function, with :
void somefunction()
{
// I have p here, which prints "404C49474854"
char text[TEXT_MAX_SIZE]={0};
textFromHexString(p,text);
}
It works, but it works 80% of the time. in some cases it crashes, where :
-incoming hex pointer is : "404C49474854". for sure .
-where the pointer temp get a completely other values that are not even inside hex.
Is there something basically wrong with this method ?
EDIT:
Check where the line that prints inside the loop, it will print this in a very specific situation :
4Hello, world
How temp, that consist of numbers only, gets this string ? (the "Hello world", is just a string I print at the beginning of the program, also temp size is 3)
You can use sscanf() to directly read hexadecimal numbers of a given length, like so:
while(hex[0] && hex[1]) {
int value;
sscanf(hex, "%2x", &value);
printf("%c", value);
hex += 2;
}
printf("\n");
It seems as if most errors were found by the commenters, so here is code that works under the assumption that I guessed right what you want.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
// ALL CHECKS OMMITTED!
void textFromHexString(char *hex, char result[])
{
// work on copy
char *p = result;
// this has more steps than necessary for clarity
for (size_t k = 1; k < strlen(hex); k += 2) {
// normalize input
char first = tolower(hex[k - 1]);
char second = tolower(hex[k]);
// convert hexbyte to decimal number
int f1 = (isdigit(first)) ? first - '0' : (first - 'a') + 10;
int f2 = (isdigit(second)) ? second - '0' : (second - 'a') + 10;
// two byte number from LSB hex to decimal (e.g.: "ab" = 171)
int num = f1 * 16 + f2;
// needs to store min. 3 characters plus NUL
char temp[4] = { 0 };
// sprintf is a bit too much for it but simple
sprintf(temp, "%d", num);
// concatenate temp to the result-string
strcat(p, temp);
// For debugging, I guess, or further work?
printf("%s\n", temp);
}
}
#define TEXT_MAX_SIZE 64
int main()
{
// 0x404C49474854 = 70696391100500
char *p = "404C49474854";
// allocate some scratchspace on the stack
char text[TEXT_MAX_SIZE] = { 0 };
textFromHexString(p, text);
// the function textFromHexString() does it in chunks of two bytes,
// so the result is 647673717284 here
printf("Result: %s\n", text);
exit(EXIT_SUCCESS);
}
A simple problem but I can't get documentation about this kind of format: I want to print a float in a Fortran scientific notation, with its integer part always being zero.
printf("%0.5E",data); // Gives 2.74600E+02
I want to print it like this:
.27460E+03
How can I get this result as clean as possible?
If you only care about the integer part being 0 and not really leaving out the 0, i.e. if you're fine with 0.27460E+03 instead of .27460E+03 you could do something similar to this:
#include <stdio.h>
#include <stdlib.h>
void fortran_printf();
int main(void)
{
double num = 274.600;
fortran_printf(num);
exit(EXIT_SUCCESS);
}
void fortran_printf(double num)
{
int num_e = 0;
while (num > 1.0) {
num /= 10;
num_e++;
}
printf("%.5fE+%02d", num, num_e);
}
Otherwise you have to take a detour over strings. Note that the code above is only meant to get you started. It certainly doesn't handle any involved cases.
I tried doing this with log10() and pow(), but ended up having problems with rounding errors. So as commented by #Karoly Horvath, string manipulation is probably the best approach.
#include <stdlib.h>
char *fortran_sprintf_double(double x, int ndigits) {
char format[30], *p;
static char output[30];
/* Create format string (constrain number of digits to range 1–15) */
if (ndigits > 15) ndigits = 15;
if (ndigits < 1) ndigits = 1;
sprintf(format, "%%#.%dE", ndigits-1);
/* Convert number to exponential format (multiply by 10) */
sprintf(output, format, x * 10.0);
/* Move the decimal point one place to the left (divide by 10) */
for (p=output+1; *p; p++) {
if (*p=='.') {
*p = p[-1];
p[-1] = '.';
break;
}
}
return output;
}
A string manipulation approach:
int printf_NoIntegerPart(double x, int prec) {
char buf[20 + prec];
sprintf(buf, "%+.*E", prec - 1, x * 10.0); // use + for consistent width output
if (buf[2] == '.') {
buf[2] = buf[1];
buf[1] = '.';
}
puts(buf);
}
int main(void) {
printf_NoIntegerPart(2.74600E+02, 5); // --> +.27460E+03
}
This will print "INF" for |x| > DBL_MAX/10
printf() will not meet OP’s goal in one step using some special format. Using sprintf() to form the initial textual result is a good first step, care must be exercised when trying to do “math” with string manipulation.
Akin to #user3121023 deleted answer.
#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
int printf_NoIntegerPart(double x, int prec) {
assert(prec >= 2 && prec <= 100);
char buffer[prec + 16]; // Form a large enough buffer.
sprintf(buffer, "%.*E", prec - 1, x);
int dp = '.'; // Could expand code here to get current local's decimal point.
char *dp_ptr = strchr(buffer, dp);
char *E_ptr = strchr(buffer, 'E');
// Insure we are not dealing with infinity, Nan, just the expected format.
if (dp_ptr && dp_ptr > buffer && E_ptr) {
// Swap dp and leading digit
dp_ptr[0] = dp_ptr[-1];
dp_ptr[-1] = dp;
// If x was not zero …
if (x != 0) {
int expo = atoi(&E_ptr[1]); // Could use `strtol()`
sprintf(&E_ptr[1], "%+.02d", expo + 1);
}
}
return puts(buffer);
}
int main(void) {
printf_NoIntegerPart(2.74600E+02, 5); // ".27460E+03"
return 0;
}
Faced same issue while fortran porting.
DId not found std C format :(
Implemented both approaches - with log10/pow and with string manipulation.
#include <ansi_c.h>
#define BUFFL 16
// using log10 , 3 digits after "."
char* fformat1(char* b, double a) {
int sign = 1;
double mant;
double order;
int ord_p1;
if (a<0) {
sign =-1;
a = -a;
}
order=log10 (a);
if (order >=0) ord_p1 = (int) order +1; // due sto property of int
else ord_p1 = (int) order;
mant=a/(pow(10,ord_p1));
sprintf(b,"%.3fE%+03d",mant,ord_p1);
if (sign==-1) b[0]='-';
return b;
}
// using string manipulation
char* fformat2(char* b, double a) {;
int sign = 1;
int i;
int N=3;
if (a<0) {
sign =-1;
a = -a;
}
sprintf(b,"%0.3E",a*10); // remember - we *10 to have right exponent
b[1]=b[0]; // 3.123 => .3123
b[0]='.';
for (i=N; i>=0; i--) // and shif all left
b[i+1]=b[i];
b[0]='0'; // pad with zero 0.312
if (sign==-1) b[0]='-'; // sign if needed
return b;
}
int main () {
char b1[BUFFL]; // allocate buffer outside.
char b2[BUFFL];
char b3[BUFFL];
char b4[BUFFL];
char b5[BUFFL];
printf("%s %s %s %s %s \n", fformat(b1,3.1), fformat(b2,-3.0), fformat(b3,3300.),
fformat(b4,0.03), fformat(b5,-0.000221));
printf("%s %s %s %s %s \n", fformat2(b1,3.1), fformat2(b2,-3.0), fformat2(b3,3300.),
fformat2(b4,0.03), fformat2(b5,-0.000221));
return 1;
}
I am looking for a (relatively) simple way to parse a random string and extract all of the integers from it and put them into an Array - this differs from some of the other questions which are similar because my strings have no standard format.
Example:
pt112parah salin10n m5:isstupid::42$%&%^*%7first3
I would need to eventually get an array with these contents:
112 10 5 42 7 3
And I would like a method more efficient then going character by character through a string.
Thanks for your help
A quick solution. I'm assuming that there are no numbers that exceed the range of long, and that there are no minus signs to worry about. If those are problems, then you need to do a lot more work analyzing the results of strtol() and you need to detect '-' followed by a digit.
The code does loop over all characters; I don't think you can avoid that. But it does use strtol() to process each sequence of digits (once the first digit is found), and resumes where strtol() left off (and strtol() is kind enough to tell us exactly where it stopped its conversion).
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
int main(void)
{
const char data[] = "pt112parah salin10n m5:isstupid::42$%&%^*%7first3";
long results[100];
int nresult = 0;
const char *s = data;
char c;
while ((c = *s++) != '\0')
{
if (isdigit(c))
{
char *end;
results[nresult++] = strtol(s-1, &end, 10);
s = end;
}
}
for (int i = 0; i < nresult; i++)
printf("%d: %ld\n", i, results[i]);
return 0;
}
Output:
0: 112
1: 10
2: 5
3: 42
4: 7
5: 3
More efficient than going through character by character?
Not possible, because you must look at every character to know that it is not an integer.
Now, given that you have to go though the string character by character, I would recommend simply casting each character as an int and checking that:
//string tmp = ""; declared outside of loop.
//pseudocode for inner loop:
int intVal = (int)c;
if(intVal >=48 && intVal <= 57){ //0-9 are 48-57 when char casted to int.
tmp += c;
}
else if(tmp.length > 0){
array[?] = (int)tmp; // ? is where to add the int to the array.
tmp = "";
}
array will contain your solution.
Just because I've been writing Python all day and I want a break. Declaring an array will be tricky. Either you have to run it twice to work out how many numbers you have (and then allocate the array) or just use the numbers one by one as in this example.
NB the ASCII characters for '0' to '9' are 48 to 57 (i.e. consecutive).
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
int main(int argc, char **argv)
{
char *input = "pt112par0ah salin10n m5:isstupid::42$%&%^*%7first3";
int length = strlen(input);
int value = 0;
int i;
bool gotnumber = false;
for (i = 0; i < length; i++)
{
if (input[i] >= '0' && input[i] <= '9')
{
gotnumber = true;
value = value * 10; // shift up a column
value += input[i] - '0'; // casting the char to an int
}
else if (gotnumber) // we hit this the first time we encounter a non-number after we've had numbers
{
printf("Value: %d \n", value);
value = 0;
gotnumber = false;
}
}
return 0;
}
EDIT: the previous verison didn't deal with 0
Another solution is to use the strtok function
/* strtok example */
#include <stdio.h>
#include <string.h>
int main ()
{
char str[] = "pt112parah salin10n m5:isstupid::42$%&%^*%7first3";
char * pch;
printf ("Splitting string \"%s\" into tokens:\n",str);
pch = strtok (str," abcdefghijklmnopqrstuvwxyz:$%&^*");
while (pch != NULL)
{
printf ("%s\n",pch);
pch = strtok (NULL, " abcdefghijklmnopqrstuvwxyz:$%&^*");
}
return 0;
}
Gives:
112
10
5
42
7
3
Perhaps not the best solution for this task, since you need to specify all characters that will be treated as a token. But it is an alternative to the other solutions.
And if you don't mind using C++ instead of C (usually there isn't a good reason why not), then you can reduce your solution to just two lines of code (using AXE parser generator):
vector<int> numbers;
auto number_rule = *(*(axe::r_any() - axe::r_num())
& *axe::r_num() >> axe::e_push_back(numbers));
now test it:
std::string str = "pt112parah salin10n m5:isstupid::42$%&%^*%7first3";
number_rule(str.begin(), str.end());
std::for_each(numbers.begin(), numbers.end(), [](int i) { std::cout << "\ni=" << i; });
and sure enough, you got your numbers back.
And as a bonus, you don't need to change anything when parsing unicode wide strings:
std::wstring str = L"pt112parah salin10n m5:isstupid::42$%&%^*%7first3";
number_rule(str.begin(), str.end());
std::for_each(numbers.begin(), numbers.end(), [](int i) { std::cout << "\ni=" << i; });
and sure enough, you got the same numbers back.
#include <stdio.h>
#include <string.h>
#include <math.h>
int main(void)
{
char *input = "pt112par0ah salin10n m5:isstupid::42$%&%^*%7first3";
char *pos = input;
int integers[strlen(input) / 2]; // The maximum possible number of integers is half the length of the string, due to the smallest number of digits possible per integer being 1 and the smallest number of characters between two different integers also being 1
unsigned int numInts= 0;
while ((pos = strpbrk(pos, "0123456789")) != NULL) // strpbrk() prototype in string.h
{
sscanf(pos, "%u", &(integers[numInts]));
if (integers[numInts] == 0)
pos++;
else
pos += (int) log10(integers[numInts]) + 1; // requires math.h
numInts++;
}
for (int i = 0; i < numInts; i++)
printf("%d ", integers[i]);
return 0;
}
Finding the integers is accomplished via repeated calls to strpbrk() on the offset pointer, with the pointer being offset again by an amount equaling the number of digits in the integer, calculated by finding the base-10 logarithm of the integer and adding 1 (with a special case for when the integer is 0). No need to use abs() on the integer when calculating the logarithm, as you stated the integers will be non-negative. If you wanted to be more space-efficient, you could use unsigned char integers[] rather than int integers[], as you stated the integers will all be <256, but that isn't a necessity.