Почему после первого заполнения структуры всё прерывается и выводит какой-то бред
объясните пожалуйста, почему после первого заполнения структуры, а именно после ввода Name Of Book всё прерывается и выводит какой-то бред.
#include <clocale>
#include <cstdlib>
#include <cstring>
#include <Windows.h>
using namespace std;
struct book
{
char title[50];
char authors[50];
char publisher[25];
int year;
unsigned int pages;
};
const int N = 3;
book collection[N]; // создаем массив из N структур book
int main()
{
setlocale(LC_ALL, "rus");
for (int i = 0; i < N; i++)
{
printf("\n\nEnter data for the book №%d\n", i + 1);
printf(" Name Of Book - ");
scanf("%79[^\n]", collection[i].title);
SetConsoleCP(866);
printf(" Author - ");
SetConsoleCP(1251);
scanf("%79[^\n]", collection[i].authors);
SetConsoleCP(866);
printf(" Publisher - ");
SetConsoleCP(1251);
scanf("%79[^\n]", collection[i].publisher);
SetConsoleCP(866);
}
char find_title[50];
printf("\n\n Enter the title of the book you are looking for - ");
SetConsoleCP(1251);
scanf("%79[^\n]", find_title);
SetConsoleCP(866);
bool found = false;
for (int i = 0; i < N; i++)
{
if (strcmp(collection[i].title, find_title) == 0)
{
found = true;
printf("\n======== FOUND BOOK ==========\n");
printf(" Name: ");
puts(collection[i].title);
printf(" Authors ");
puts(collection[i].authors);
printf(" Publisher: ");
puts(collection[i].publisher);
printf(" Year of issue: %d\n", collection[i].year);
printf(" Pages %u\n", collection[i].pages);
}
}
if (!found)
printf(" A book with this title was not found in the collection.!\n");
system("pause");
return 0;
}
Бред:
Enter data for the book в"-1 Name Of Book - fekekef Author - Publisher -
Enter data for the book в"-2 Name Of Book - Author - Publisher -
Enter data for the book в"-3 Name Of Book - Author - Publisher -
Enter the title of the book you are looking for - ======== FOUND BOOK ========== Name: Authors Publisher: Year of issue: 0 Pages 0
Ответы (2 шт):
Автор решения: gbg
→ Ссылка
- Писать
scanf/printfи при этом использовать плюсовый компилятор - как минимум дурной тон. Если пишете наC++, пользуйтесьC++(cin,cout) - Ваша проблема в том, что у вас в форматной строке у
scanfнету\n. Так что символ перевода строки остается в буфере, от чего весь последующий ввод оказывается поломан.
Автор решения: Harry
→ Ссылка
Вам некуда деть \n в буфере ввода — его никто не принимает. Напишите так, например:
scanf("\n%79[^\n]", collection[i].title);
printf(" Author - ");
scanf("\n%79[^\n]", collection[i].authors);
printf(" Publisher - ");
scanf("\n%79[^\n]", collection[i].publisher);
Только вот длины буферов у вас 50, 50 и 25, а вы им всем позволяете читать по 79 символов. Нехорошо...