• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 181
  • Last Modified:

handling a string


I have a textfile containing text and numbers, like this :

Abc 34yfg 690
5 90 8

What I need is a short function on how to extract the numbers from this text and add them together.

The text above = 34 + 690 + 5 + 90 + 8 +1

1 Solution
well, I hope that it's not homework. I won't code it for you in anycase, but here's some idea.

  SInce it's a text file, use 2 nested loops.
  the outer loop reads each line of the file with gets()
   the inner loop finds each 'word' by repeatedly calling strtok()
     for each 'word' if isalpha() returns false then it's a number *
     so, add it to the total.

* is alpha will return false if you have a non-alphabetical character, this includes all digits, but also all punctuation :[]{}(),. etc  Maybe you want to write a quick isDigitsOnly()

int isDigitsOnly(char *token)
  for (int i = o; i < strlen(token); i++)
    if (!isdigit(token[i]))
      return 0;  // non-digit, return false

  return 1;  // all were digits, return true

There is a simple function to test if a character is a digit, int isdigit(int thechar).
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

Tackle projects and never again get stuck behind a technical roadblock.
Join Now