if i have input like this
1 2 3
1 3 4
2 4 5
i use get line to read it and use sscanf to get their value to store ia array.
anyone has any better way to deal with it? plz advise
if i have input like this
1 2 3
1 3 4
2 4 5
i use get line to read it and use sscanf to get their value to store ia array.
anyone has any better way to deal with it? plz advise
Here's another way :-)
Code:#include <stdio.h> #include <stdlib.h> #include <string.h> enum {MAX_INT = 9, MAX_LINE = 100}; int main(void) { size_t i; /* Scratch index */ size_t index; /* Index for the int array */ int a[MAX_INT]; /* Array for the list of ints */ char buff[MAX_LINE]; /* File buffer, holds one line */ FILE *fp; /* Input file */ if ((fp= fopen("input.txt", "r")) == 0) { perror("File open failure"); return 1; } index = 0; while (fgets(buff, sizeof(buff), fp) != 0 && index < MAX_INT) { char *newline; /* Used to find and remove the newline */ char *current; /* Marks the current location in the string */ if ((newline = strrchr(buff, '\n')) != 0) /* Remove the trailing newline left by fgets */ { *newline = '\0'; } current = buff; while (*current != '\0') /* Get a line of ints, no limit assumed */ { a[index++] = strtol(current, ¤t, 0); } } /* Check that it worked */ for (i = 0; i < index; i++) { printf("%d\n", a[i]); } fclose(fp); return 0; }
*Cela*
Well, depending upon just HOW you're doing this, it might not be so bad. If people could see your code, then they'd tell you if they saw any problems with your particular execution or implimentation of the code.
scanf isn't so bad ..with some things, we just need to see how you're using all this stuff
- edit -
wel, someone went ahead and answered ya
...and, I have an AVATAR...ACK!! I thought I removed that...dam..
The world is waiting. I must leave you now.
i want to get inputs from standard input. how can i know that the input is end
ex. 2 first line indicaye how many line left
1 2 3
2 3 4
'
'
'
Thanks u guys
Have a go yourself, and post some code when you get stuck.
>how can i know that the input is end
When you post your code, I'll get to see what function you're using to read in the data. I'd guess it's fgets(), in which case that function will return NULL when it reaches the end of the input.
When all else fails, read the instructions.
If you're posting code, use code tags: [code] /* insert code here */ [/code]
>>i want to get inputs from standard input. how can i know that the input is end
The code I gave you can take input from stdin just as easily, all you have to do is change this
to this :-)Code:if ((fp= fopen("input.txt", "r")) == 0) { perror("File open failure"); return 1; }
And don't forget to remove this :-)Code:fp = stdin;
Code:fclose(fp);
*Cela*