1

I am trying to create a function in C that divides a string based on two spaces:

char *string = "10234540234  the";

I want get_weight() to return

10234540234

Here is how my function is defined

long get_weight(char *string) {
    long length = strlen(string);
    printf("%c \n", string[11]);
    char *number[200];
    int count = 0;
    for (int i = 0; i < length; i++) {
        if (string[i] == " " && string[i+1] == " ") {
            break;
        } else {
            number[count] = string[i];
            count++;
        }
    }
    return atol(number);
}

It goes into an infinite loop, and I am not sure why...

7
  • 1
    Try to add a \0 at the end of number Commented Feb 16, 2021 at 17:47
  • Fyi, return atol(number); should be flagging a compiler warning. The function requires const char *, you're passing anything-but. Commented Feb 16, 2021 at 17:50
  • You do realize just atol("123 xyz") would also return 123? Commented Feb 16, 2021 at 18:01
  • You would get the same result with long get_weight(char *string) { return atol(string); }. because atoi will stop at the first wrong character. For better error checking I suggest to use strtol instead of atol. Commented Feb 16, 2021 at 18:04
  • Why not use sscanf? Commented Feb 16, 2021 at 18:21

1 Answer 1

2

There were several issues in your code

  • Comparison of string[i] must be with a character
  • char number[200]; and not char *number[200];
  • Terminaison of the new string with '\0'
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

long get_weight(char *string) {
    long length = strlen(string);
    char number[200];
    int count = 0;
    for (int i = 0; i < length; i++) {
        if (string[i] == ' ' && string[i+1] == ' ') {
            break;
        } else {
            number[count] = string[i];
            count++;
        }
    }
    number[count] = '\0';
    return atol(number);
}

int main() {
    char str[] = "12346  abc";
    long num = get_weight (str);
    printf ("number = %ld\n", num);
}

Note that as mentioned in comments, if the goal is only to get the leading number, and not to split the input string as the title suggests, you could have only used

return atol(string);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.