-3

I have this .txt file that contains only:

THN1234 54

How can I take only the number 54, to isolate it from the rest and to use it as an integer variable in my program?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • This question doesn't make sense at all. There is no general question because you probably don't have the slightest idea yet. You can't ask here then! You should write some code and if it fails you come to SO and ask, post the code and say I think this should do X but it's doing Y, can you help me find the problem? – Iharob Al Asimi Nov 14 '16 at 23:31
  • 3
    `fscanf(fp, "%*s %d", &value);` – BLUEPIXY Nov 14 '16 at 23:33

2 Answers2

0

Wow. It's been a long time since I have used C. However, I think the answer is similar for C and C++ in this case. You can use strtok_r to split the string into tokens then take the second token and parse it into an int. See http://www.cplusplus.com/reference/clibrary/cstring/strtok/.

You might also want to look at this question as well.

Community
  • 1
  • 1
melston
  • 2,198
  • 22
  • 39
  • It worries me when the answer is `strtok()` — it isn't the first alternative that comes to mind, not least because it still leaves the 'conversion to `int`' undone. – Jonathan Leffler Nov 15 '16 at 00:08
  • True. But we are talking C, here. The problem included ignoring an initial portion of the string so I didn't want to start with sscanf or equivalent. – melston Nov 15 '16 at 20:31
0

If the input is from standard input, then you could use:

int value;

if (scanf("%*s %d", &value) != 1)
    …Oops - incorrectly formatted data…
…use value…

The %*s reads but discards optional leading blanks and a sequence of one or more non-blanks (THN1234); the blank skips more optional blanks; the %d reads the integer, leaving a newline behind in the input buffer. If what follows the blank is not convertible to a number, or if you get EOF, you get to detect it in the if condition and report it in the body of the if.

Hmmm…and I see that BLUEPIXY said basically the same (minus the explanation) in their comment, even down to the choice of integer variable name.

Community
  • 1
  • 1
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278