|
0 / 0 / 0
Регистрация: 03.10.2013
Сообщений: 24
|
|
Работа с текстовыми файлами30.11.2013, 19:36. Показов 436. Ответов 0
Метки нет (Все метки)
Есть готовая программа, но надо переделать, что бы в 4 case вместо сортировки, можно было найти студента, у которого имя и фамилия (из списка) совпадает с теми, что ввел пользователь.
Исходный файл что то вроде такого. заранее спасибо!) 0 Uwe Boll 32 12 44 1 Valentin Strikalo 22 03 92 2 Eugene Belnikov 12 8 66 3 Ratibor Berestov 06 02 67 4 Peter Sundae 22 04 55 5 Janis Licis 13 07 22 6 Peter Dolgov 28 12 52 7 Hao Lichen 12 07 22 8 Ferdinand Lihachev 12 02 22 #include <stdio.h> #include <conio.h> #include <string.h> //libraries #include <windows.h> #define N 20 int main() { struct individual //define structure for { // Nr., Name, Surname, DOB int Nr; char name[30], surname[30]; struct birth { int day; //hell yeah a structure within a structure int month; //INCEPTION int year; }date; }student[N],temp[1]; int i, j, last,out,choice, exists; //some handy variables FILE *list; //will be operating in two files FILE *list_sorted; //original and edited system("cls"); out=0; //initialize some stuff j=0; exists=0; last=0; do //a while loop for menu { //useful stuff. but takes a shitton of time to debug system("cls"); printf("MENU:\n1.Aizpildit sarakstu no faila.'studenti.txt'.\n2.Papildinat sarakstu ar rokam.\n"); printf("3.Paradit sarakstu.\n4.Sakartot sarakstu pec dzimshanas datuma un uzvarda\n5.Saglabat datus\n6.Iziet\n"); scanf("%d", &choice); switch(choice) { case 1: //case 1 to scan a file and read all data from it. list = fopen ("studenti.txt", "r"); //file is prepared specially //red in sequential way if (list == NULL ) { printf ("Nevar atvert failu \n"); system("pause"); exit (1); } for(i=0; i<N; i++) { //since there is no way to return the number of the lines in a file fscanf(list, "%d", &student[i].Nr); //and if we try to return a nonexistent line, it will se the pointer to the end of line fscanf(list, "%s", &student[i].name); //the return will be gibberish, but the pointer will stand on the same way before fscanf(list, "%s", &student[i].surname); //and after the attempt to read stuff. fscanf(list, "%d", &student[i].date.day); //therefore, if we see that pointer position doesnt change, we know ir is at the end.fscanf(list, "%1c"); fscanf(list, "%d", &student[i].date.month); //if so, we break out of the loop for it is set to go through the maximum list size N. fscanf(list, "%d", &student[i].date.year); if (feof(list)) { last=i; break; } } fclose(list); exists=1; //tiny variable for later use, to avoid processing empty list break; case 2: choice=0; while (choice!=1) { student[last].Nr = last; printf("\nIevadiet %d. studenta informaciju\n", last); printf("Vards: "); scanf("%s", &(student[last].name)); printf("Uzvards: "); scanf("%s", &(student[last].surname)); //manual input of data into structure. printf("Dzimshanas datums. DIENA: "); scanf("%2d", &(student[last].date.day)); printf("Dzimshanas datums. MENESIS: "); scanf("%2d", &(student[last].date.month)); printf("Dzimshanas datums. GADS: "); scanf("%2d", &(student[last].date.year)); printf("\n Pievienot vel? (1=beigt)"); //in order to give user the freedom to choose how many scanf("%d", &choice); //items to add, we ask him at the end of every loop. last++; //this way ca avoid making him write in t once 20 lines. } exists=1; break; case 3: system("cls"); if (exists>0) //here's where we need the exists variable. if we don't have { //a check for structure existance, the compiler goes bananas trying to print. printf("Studentu saraksts:\n"); for(i=0; i<last; i++) { printf("%2d%15s%15s%10d.%2d.%2d\n", student[i].Nr, student[i].name, student[i].surname, student[i].date.day, student[i].date.month, student[i].date.year); } }else printf("Ludzu izveidojiet sarakstu!\n"); system("pause"); case 4: system("cls"); if (exists>0) { printf("Sakartots saraksts:\n"); for (j=0;j<last;j++) { for (i=0; i<last;i++) { if (student[i].date.year>student[j].date.year) { temp[0]=student[j]; student[j]=student[i]; student[i]=temp[0]; } else if(student[i].date.year==student[j].date.year && student[i].date.month>student[j].date.month) { temp[0]=student[j]; student[j]=student[i]; student[i]=temp[0]; } else if(student[i].date.year==student[j].date.year && student[i].date.month==student[j].date.month && student[i].date.day>student[j].date.day) { temp[0]=student[j]; student[j]=student[i]; student[i]=temp[0]; } else if(student[i].date.year==student[j].date.year && student[i].date.month==student[j].date.month && student[i].date.day==student[j].date.day && (strcmp(student[i].surname,student[j].surname)>0)) { temp[0]=student[j]; student[j]=student[i]; student[i]=temp[0]; } } } for(i=0; i<last; i++) { printf("%2d%15s%15s%10d.%2d.%2d\n", student[i].Nr, student[i].name, student[i].surname, student[i].date.day, student[i].date.month, student[i].date.year); } }else printf("Ludzu izveidojiet sarakstu!\n"); system("pause"); break; case 5: system("cls"); if (exists>0) { list_sorted = fopen ("studenti_apstradats.txt", "w"); if (list_sorted == NULL ) { printf ("Nevar atvert failu \n"); system("pause"); exit (1); } for(i=0; i<last; i++) { fprintf(list_sorted,"%2d%15s%15s%10d.%2d .%2d\n", student[i].Nr, student[i].name, student[i].surname, student[i].date.day, student[i].date.month, student[i].date.year); } fclose(list_sorted); printf ("Dati sekmigi saglabati faila 'studenti_apstradats.txt'! \n"); }else printf("Ludzu izveidojiet sarakstu!\n"); system("pause"); break; case 6: out=1; break; default: system("cls"); printf("Ludzu izveidojiet sarakstu!\n"); system("pause"); break; } } while(!out); out=0; return 0; }
0
|
|
| 30.11.2013, 19:36 | |
|
Ответы с готовыми решениями:
0
Работа с текстовыми файлами Работа с текстовыми файлами
|
| 30.11.2013, 19:36 | |
|
Помогаю со студенческими работами здесь
1
Работа с текстовыми файлами Работа с текстовыми файлами Работа с текстовыми файлами Работа с текстовыми файлами Работа с текстовыми файлами Искать еще темы с ответами Или воспользуйтесь поиском по форуму: |
|
Новые блоги и статьи
|
||||
|
Thinkpad X220 Tablet — это лучший бюджетный ноутбук для учёбы, точка.
Programma_Boinc 23.12.2025
Рецензия / Мнение/ Перевод
Нашел на реддите интересную статью под названием The Thinkpad X220 Tablet is the best budget school laptop period . Ниже её машинный перевод.
Thinkpad X220 Tablet —. . .
|
PhpStorm 2025.3: WSL Terminal всегда стартует в ~
and_y87 14.12.2025
PhpStorm 2025. 3: WSL Terminal всегда стартует в ~ (home), игнорируя директорию проекта
Симптом:
После обновления до PhpStorm 2025. 3 встроенный терминал WSL открывается в домашней директории. . .
|
Как объединить две одинаковые БД Access с разными данными
VikBal 11.12.2025
Помогите пожалуйста !! Как объединить 2 одинаковые БД Access с разными данными.
|
Новый ноутбук
volvo 07.12.2025
Всем привет.
По скидке в "черную пятницу" взял себе новый ноутбук Lenovo ThinkBook 16 G7 на Амазоне:
Ryzen 5 7533HS
64 Gb DDR5
1Tb NVMe
16" Full HD Display
Win11 Pro
|
Музыка, написанная Искусственным Интеллектом
volvo 04.12.2025
Всем привет. Некоторое время назад меня заинтересовало, что уже умеет ИИ в плане написания музыки для песен, и, собственно, исполнения этих самых песен. Стихов у нас много, уже вышли 4 книги, еще 3. . .
|
|
От async/await к виртуальным потокам в Python
IndentationError 23.11.2025
Армин Ронахер поставил под сомнение async/ await. Создатель Flask заявляет: цветные функции - провал, виртуальные потоки - решение. Не threading-динозавры, а новое поколение лёгких потоков. Откат?. . .
|
Поиск "дружественных имён" СОМ портов
Argus19 22.11.2025
Поиск "дружественных имён" СОМ портов
На странице:
https:/ / norseev. ru/ 2018/ 01/ 04/ comportlist_windows/
нашёл схожую тему. Там приведён код на С++, который показывает только имена СОМ портов, типа,. . .
|
Сколько Государство потратило денег на меня, обеспечивая инсулином.
Programma_Boinc 20.11.2025
Сколько Государство потратило денег на меня, обеспечивая инсулином.
Вот решила сделать интересный приблизительный подсчет, сколько государство потратило на меня денег на покупку инсулинов.
. . .
|
Ломающие изменения в C#.NStar Alpha
Etyuhibosecyu 20.11.2025
Уже можно не только тестировать, но и пользоваться C#. NStar - писать оконные приложения, содержащие надписи, кнопки, текстовые поля и даже изображения, например, моя игра "Три в ряд" написана на этом. . .
|
Мысли в слух
kumehtar 18.11.2025
Кстати, совсем недавно имел разговор на тему медитаций с людьми. И обнаружил, что они вообще не понимают что такое медитация и зачем она нужна. Самые базовые вещи. Для них это - когда просто люди. . .
|