I understand this is a basic qu开发者_Go百科estion... but I have been stuck on it for an hours. I'm kind of new to C. I have been trying to parse in some integers from a textfile thats located in a particular fashion. Here is an example:
A 123,1
B 456,2
N 980,2
I want to throw out the letters, and the number after the commas. Hence, I would have just 123, 456, and 980. I have been getting stuck on the first part (throwing out the letters, and the white space in between has been screwing with me :( ). I know there have been numerous posts that are somewhat similar, but I can't seem to be able to get it. Here is my code so far (test.txt contains the input values).
int main(void)
{
FILE *rFile = fopen ("test.txt", "rt");
char input[20];
if (rFile == NULL) {
printf("Input file could not be located");
return -1;
}
while (fscanf(rFile, "%s \n", input) > 0)
{
printf("%s", input);
}
fclose(rFile);
return 0;
}
This is obviously not complete. My way about solving this problem is to take the input string (including the white spaces) and then use the strtok to cut out the middle part. However, I can't even parse in each line of the textfile properly.
scanf
works fine for selectively reading in only a portion of the input.
int num;
scanf("%*c %d,%*d",&num);
printf("%d\n",num);
scanf
ignores whitespace before the %d
and having an asterisk in the format string (e.g. in %*c
and %*d
) makes it read in and then throw away that token, freeing us from specifying variables to store the parts of input that we do not need.
scanf
and fscanf
can also parse single characters and integers. It ignores whitespace before entities.
char c ;
int n1 ;
int n2 ;
// ...
while (fscanf(rFile, "%c %d,%d ", &c, &n1, &n2) > 0)
{
printf("%d\n", n1);
}
If you're looking to load an entire line of text, whitespace included, you're probably better off using fgets
instead of fscanf
.
char* fgets (char* stringBuffer, int numberOfCharacters, FILE* fileStream);
fgets
will keep reading until one of the following conditions is met:
- Newline is reached
- End of file is reached
- Number of characters (minus one) is reached
With the 20 character string buffer in your example, you could use something like this:
while (fgets(input, 20, rFile)) {
printf("%s", input);
}
That said, junjanes solution is probably still the better fit for your exact problem.
精彩评论