#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[]) {
FILE *datei;
char text[100];
char line[128], *p;
int il;
datei = fopen ("data.txt", "r");
if (datei != NULL){
if (fgets(line, sizeof(line), datei) != 0){ //read one line
p=strrchr(line, ' ');//search last space
*p = '\0';//split at last space
strcpy(text, line);
il = atoi(p+1);//or sscanf(p+1, "%d", &il);
printf("%s, %d", text, il);
}
fclose(datei);
}
return 0;
}
也使用 fscanf。
char *p;
//"%[^0123456789] is reading other digit character
fscanf(datei, "%[^0123456789]%d", text, &il);
p=strrchr(text, ' ');//search last space
*p = '\0';//replace last space (meant drop)
printf("%s, %d", text, il);
手工制作的?
#include <ctype.h>
if (datei != NULL){
int ch, i=0;
while(EOF!=(ch=fgetc(datei)) && i<100-1){
if(isdigit(ch)){
ungetc(ch, datei);
text[--i] = '\0';
break;
}
text[i++] = ch;
}
if(i >= 99){
fprintf(stderr, "It does not conform to the format\n");//maybe no
fclose(datei);
return -1;
}
fscanf(datei, "%d", &il);
printf("%s, %d\n", text, il);
fclose(datei);
}