问题
I need to create a phonebook in C, with structs and linked-list.
Data will be on a file. I'll store data like
Name1#Surname1#Date1#Number1
Name2#Surname2#Date1#Number2
Name3#Surname3#Date1#Number3
But I couldn't split by delimiter "#" and use datas in my struct. Here is my code:
#include <stdio.h>
#include <locale.h>
//Veri Yapısı:
typedef struct kisi
{
char isim[50];
char soyisim[50];
int dYili;
char telefon[16];
struct kisi *sonraki;
}Kisi;
int main()
{
//Türkçe çıktılarda sorun yaşamamak için:
setlocale(LC_ALL,"Turkish");
//Dosya yolunu sabitle:
char *dosyaYolu = "rehber.dat";
//Dosyayı aç:
FILE *dosya;
//Okuma modunda
dosya = fopen(dosyaYolu,"r");
//Eğer dosya açılmazsa:
if(dosya == NULL)
{
printf("Dosya açılamadı. Yolu doğru girdiğinizden emin olun.\n===============================\n\n");
main();
}
//Dosya açıldı.
else
{
Kisi *liste = (Kisi*)malloc(sizeof(Kisi));
Kisi *iter = liste;
//Dosyanın sonuna kadar oku:
while(!feof(dosya))
{
char *veri;
fscanf(dosya,"%s",veri);
char *tok = strtok(veri, "#");
int sayac = 0;
while(tok != NULL)
{
switch(sayac)
{
case 0: strcpy(iter->isim,tok);
break;
case 1: strcpy(iter->soyisim,tok);
break;
case 2: iter->dYili = (int)tok;
break;
case 3: strcpy(iter->telefon,tok);
break;
}
sayac++;
tok = strtok(NULL, "#");
}
iter->sonraki = (Kisi*)malloc(sizeof(Kisi));
iter = iter->sonraki;
}//while sonu
//Dosyayla işimiz bitti. Kapat:
fclose(dosya);
}
system("pause>null");
}
What I need to do is:
- Read data from a file
- Use data for struct
- Link structs
- Add a new person, delete a person etc. (I didn't try to do them yet, there's nothing about this in my code)
My problem is, when I run this program, it stops working. When I remove that while loop with switch-case and just printf my token, it works.
Additional information:
- I've to use a file to store my data
- I've to use structs and linked lists
- Every person must be in its own struct (1 struct = 1 person, the same struct of course)
- This program cannot contain C++ codes.
回答1:
You have 2 important problems causing undefined behavior and hence the problem in your program
You don't allocate space for
veri
in the outerwhile
loopchar *veri; fscanf(dosya,"%s",veri);
you should at least do something like
char veri[100]; fscanf(dosya,"%99s",veri);
You assign the value of a pointer to an
int
iter->dYili = (int)tok
you should, convert the string to an
int
by means ofstrtol
this wayiter->dYili = strtol(tok, NULL, 10);
if you want to check for conversion error delcare a
char *endptr;
at the beginig of the loop and do thisiter->dYili = strtol(tok, &endptr 10); if (*endptr != '\0') anErrorOccurredHandleIt();
Also, don't forget to free
all the malloc
ed pointers, and I think fgets
would do a better job in this situation.
来源:https://stackoverflow.com/questions/27807662/c-split-string-and-use-it-for-struct