Hi, first post. I'm trying to read numbers from a file with strtok and for some reason the last value in the file is printed twice.
[Example] input: 1 2 5 word 4
output: 1 2 5 4 4
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 100
int isNumeric(char*);
int main (int argc,char* argv[]){
if(argc!=2){
puts("Usage: ./HW1 <filename>.txt");
return 0;
}
FILE* cfPtr;
if((cfPtr=fopen(argv[1],"r"))==NULL){
puts("File could not be opened");
return 0;
}
double test;
char line[SIZE];
char* strPtr;
char* tokenPtr;
while(!feof(cfPtr)){
fgets(line,SIZE,cfPtr);
tokenPtr=strtok(line," \t\n");
while(tokenPtr!=NULL){
printf("tokenPtr:%s\n",tokenPtr);
if(isNumeric(tokenPtr)){
test=strtod(tokenPtr,&strPtr);
printf("%.0f\n", test);
}
tokenPtr = strtok(NULL," \t\n");
}
}
fclose(cfPtr);
return 0;
}
int isNumeric(char* token){
int i=0;
if(token[i]=='-'){
++i;
}
if(token[i]=='\0'){
return 0;
}
while(token[i]!='\0'){
if(isdigit(token[i])==0){
return 0;
}
++i;
}
return 1;
}