#pass a number as string to function and return it as string(no libraries at all).

14 messages · Page 1 of 1 (latest)

elfin star
#

For example if input "-1" then output -1
if input "+1" then output 1
if input "1,01" then output 1,01
now my Task is to write a condition to get an output 1 if the input for example "1,000" so I have to clean all zeros after the comma and clean the comma too. Hope You can help and thnx in advance.

here is my function :

char *str_dup(const char * const str)
{
unsigned long length = 0;
for(int i = 0; str[i] != '\0'; i++)
length++;

char *new_str = malloc(sizeof(char) * (length + 1));
for(int i = 0; str[i] != '\0'; i++){
    if (str[0]=='+')
    {
        new_str[i] = str[i+1];
    }
    else
    {
        new_str[i] = str[i];
    }
    }

new_str[length] = '\0';

return new_str;

}

stable gazelleBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question run !howto ask.

stable gazelleBOT
#

For example if input "-1" then output -1
if input "+1" then output 1
if input "1,01" then output 1,01
now my Task is to write a condition to get an output 1 if the input for example "1,000" so I have to clean all zeros after the comma and clean the comma too. Hope You can help and thnx in advance.

here is my function :

char* str_dup(const char* const str) {
  unsigned long length = 0;
  for (int i = 0; str[i] != '\0'; i++)
    length++;

  char* new_str = malloc(sizeof(char) * (length + 1));
  for (int i = 0; str[i] != '\0'; i++) {
    if (str[0] == '+') {
      new_str[i] = str[i + 1];
    } else {
      new_str[i] = str[i];
    }
  }

  new_str[length] = '\0';

  return new_str;
}
Hashious
loud cove
#

I would create a struct containing the decimal and the fraction parsed from the string

#

And use the struct object as reference what the new string would be like

#

Doesn't have to be a struct tho

elfin star
#

you mean i have to split the string into after comma digits (decimals) and before comma digits? and then check if decimals sum is bigger than zero or not ?

loud cove
#

No need to actually split the string, just parse the string for example in your case {sign}[decimals]{comma fractions}

#

By no libraries at all you meant not a single libc or just the string manipulation functions? cuz malloc is a libc function

elfin star
#

no libraries at all we have to call malloc like that void malloc(size_t size);

molten eagle
#

malloc is from a library though

split juniper
#

Is this a university lecturer making assignments absolutely difficult for no reason again?

stable gazelleBOT
#

This question thread is being automatically closed. If your question is not answered feel free to bump the post or re-ask. Take a look at !howto ask for tips on improving your question.