I want to read from a file which stores data like this:
Max Mustermann 12345
Now I want to read the data with this code:
FILE *datei;
char text[100];
int il;
datei = fopen ("datei.txt", "r");
if (datei != NULL)
{
fscanf(datei, ": %s %d", text, &il);
printf("%s %d", text, il);
fclose(datei);
}
But this code scans only 'Max' (because there is a whitespace) and then the next 'Mustermann' as int. I want to sotre 'Max Mustermann' is the char array and '12345' in the int varaible. What can I do to read whitespaces with fscanf? Or is there an other way to get values in different varaibles from the file?
#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;
}
also use 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);
hand made?
#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);
}
It depends on the format of the file. If it is always first-name space last-name space number
then you can use two %s to get first and last name.
if (fscanf(datei, "%s %s %d", text1, text2, &il) == 3)
...then OK...
else
...failed...
If for example, the number is preceded by a special/unique character (let's say a "!") then you can use a scanf format like this ?
if (fscanf(datei, "%[^!]!%d", text, &il) != 2)
...
Unless you can guarantee there are always two names before the number, or the file can be delimeted (maybe a comma between name and number), then there isn't really any way to do what you want, automatically.
What if the name was: Max Mustermann 3rd
I think the data input file needs 'cleaning' before you can process it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.