PeteD PeteD - 11 days ago 5
C Question

How to use char from fscanf as int

Hello this may be a stupid question, but I cannot figure it out for the world of me! (in c)

I'm trying to read a file like with both numbers and letter, but I want to use only the numbers in my programming stuff. That look like this:

t1 stuff 12 123 stuff
t1 stuff 12 123 stuff
t1 stuff 12 123 stuff
t2 stuff 12 123 stuff
t2 stuff 12 123 stuff
t3 stuff 12 123 stuff
t4 stuff 12 123 stuff
t4 stuff 12 123 stuff
t4 stuff 12 123 stuff
t33 stuff 12 123 stuff


(it do this all the way to t33 i just skipped from t4 to t33 to avoid big list)

The way I done it is:

Struct name {
char t_numbers
etc..


and:

info(struct name*stuff) {
FILE *data;
data= fopen("thefilename", "r");
int i=0;
while (fscanf(file, "%s %s %d %d %s\n",stuff[i].t_numbers, etc etc...) == 5)
...


Now I tried to do t_numbers first as int and t%d instead of char, but because of the "T" in the file it can only be done as char and then s%.

The problem is, how can I use the stuff[i].t_numbers as a int instead of pointer? So it use the numbers and not the "T" in it.

Example:

while (k<=10) {
while (stuff[i].t_numbers==n) {


Will ofc not work because it's a pointer being compared to int. But how to make it work? How to use those data without the "T" so i can do that.

I'm extremely sorry for if it's a stupid question or if it already been asked (searched everywhere). I am totally new to this.

(the codes can have spelling mistakes etc. since it was just a fast draft as example)

Answer

As per my understanding you want just numbers from t1,t2,t3,...

I have a simple solution. It works only if there is one character at the beginning.

Change your code to read one character before int as below.

info(struct name*stuff) {
  FILE *data;
  data= fopen("thefilename", "r");
  int i=0;
  char dummyT = 0;
  while (fscanf(file, "%c%d %s %d %d %s\n",&dummyT, stuff[i].t_numbers, etc etc...) == 5)