Pregunta

I have problem with scanning a string from a file until integer value appears. If I try fgets(str,30,file); it scans everything in a single line of file, including the integer.

Example of file:

Audi 2014
Wall Street 1995
The number of words used in one line may vary 9999

Integer is always last but number of words before value is not always the same, so code like fscanf(file,"%s %s %d", str1, str2, &integer); does not work as well. My intention is to scan everything until the integer value in string and than scan the integer separately. Any ideas ?

Thanks guys.

¿Fue útil?

Solución

This is bare bones C, no fancy stuff. It will work if your data has the format you described, i.e. space separated words in a text file with the number of each line right before the newline character, and each line starts with at least one word that is not your number. Size of the buffer can change as you like, it will only affect performance. Also, your file needs to have at least one line in the format you describe.

FILE *f;
char bf[2048];
char *p, *p1;
int line, i, num;

f = fopen("mydatafile.txt", "r");
if (f)
{
    line = 0;
    while (!feof(f))
    {
        fgets(bf, sizeof(bf), f);
        p1 = bf;
        p = strchr(bf, '\n');
        while(p)
        {
            *p = 0;
            i = 0;
            while (isdigit(p[--i])) ;
            num = atoi(p+i+1);
            p[i] = 0;
            printf("line %d: %s  number = %d\n",++line, p1, num);
            p1 = p+1;
            p = strchr(p1, '\n');
        }
    }
    fclose(f);
}

For your sample data the output is:

line 1: Audi  number = 2014
line 2: Wall Street  number = 1995
line 3: The number of words used in one line may vary  number = 9999

Otros consejos

Read with fgets and do a single pass through the string while(!isdigit[str[i++]); to get to the starting position of number. Then atoi from that position and put a '\0' there

fgets(str,30,file);
int i = 0;
while(str[i]!='\0' && !isdigit(str[i]))
    i++;
int num = atoi(str + i);
str[i] = '\0';

Now the number is in num and the string before it is in str

Read the whole line and do your own parsing, or use fscanf. Pattern "%29[^0-9] %d" or something alike.

If you only need those numbers in your input lines, you could using the following code to achieve your goal

    while (scanf("%*[^0-9]%d", &num) == 1) {

That * indicates that the non-digit characters before the number will be ignored.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top