简体   繁体   中英

how to cut a string in C

I have an document with some telephone number and andresses. I now try to copy the numbers in one part of a struct and the adress into another. At the moment I was just able to get the data of the document but I can't put it in my struct please help me

C Code

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>

struct telefon{
    char nummer[16];
    char adresse[128];
};

typedef struct telefon TELEFON;

void main()
{
    TELEFON tel;
    char buffer[256];
    FILE *fp;
    int i = 0;
    int countSemi = 0;

    fp = fopen("Telefondatei.txt", "r");

    if(fp == NULL) 
    {
        printf("Datei konnte nicht geoeffnet werden.\n");
    }
    else{

        while(fgets(buffer,1000,fp) != 0){
            //printf("%s\n",buffer);
            while(buffer != 0){
                i++;
                if(buffer[i] == ';'){
                    countSemi++;
                }
                while(countSemi <= 7){
                    strcpy(tel.adresse,buffer);
                    printf("%s\n %d \n",tel.adresse,countSemi);
                }
            }
        }
    }
}

Example for the data in my .txt document

"Firma";"";"Auto GmbH";"gasse 3";"5000";"Mon";"";"0456";"45652" "Firma";"";"ADAC";"";"50000";"Mon";"";"2156";"545218"

You will need to use strtok additionally. See this example. However, please note this example assumes the data is written in fixed format (and it will not work if data comes in other format - you might want to modify this for your needs, this is just illustration):

Assumed data format for each line:

Address;telephoneNumber;

#include <string.h>
..
char * value;
while(fgets(buffer,256,fp) != 0)
{
   value = strtok(buffer, ";"); // get address
   strcpy(tel.adresse, value);

   value = strtok(NULL, ";"); // get number
   strcpy(tel.nummer, value);

}

Also this:

while(buffer != 0)

in your code doesn't make sense. Hardly buffer will be 0. It is array and value of buffer will always be memory address where that array starts. You can't assign to buffer .

Here is another post about using strtok .

To get your data use : fscanf(fp, "%s %s %s %d", str1, str2, str3, &number); or you can use getc to get one character but u need to test the EOF

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM