scanf

Содержание
Пример
Разберемся с вводом чисел
Другие статьи о Си

Пример использования функции scanf()

#include <stdio.h> int main() { char website[20]; // не забудьте указать предполагаемую максимальную длину в [] // если Вы её не укажите то по умолчанию будет всего один символ // и при вводе более длинного сообщения scanf вернёт NULL printf("Type your website name:\n"); scanf("%s", website); printf("You typed %s \n", website); return 0; }

gcc -o scanf scanf.c
./scanf

Type your website name: topbicycle.ru You typed topbicycle.ru

Обратите внимание, что для использования scanf() не нужно подлючать дополнительных библиотек.

Мне хватило #include <stdio.h>

Не забудьте указать размер массива

Не забудьте, что когда Вы собираетесь считывать символы это надо обозначить при вызове функции с помощью %s

scanf("%s", website);

Попробуйте теперь изменить код дописав & к website

scanf("%s", &website);

Ничего не дожно измениться

Разберемся с вводом чисел

#include <stdio.h> int main() { char website[20]; int year; printf("Type your website name:\n"); scanf("%s", website); // do not need to use & because it is an array printf("Which year it was made:\n"); scanf("%d", &year); // need to use & printf("You website is %s. It was made in %d \n", website, year); return 0; }

Обратите внимание на

scanf("%d", &year);

Во всех случаях кроме массива ставить & обязательно.

Если Вы напишите просто year, то получите Segmentation fault (core dumped) во время выполнения программы.

Пишем &year, компилируем и выполняем.

gcc -o scanf scanf.c
./scanf

Type your website name: heihei.ru Which year it was made: 2018 You website is heihei.ru. It was made in 2018

scanf() успешно справился и с массивом символов и с числом.

Article author: Andrei Olegovich

Похожие статьи
Программирование на Си
Основы Си
Учебник по Си
Boolean в Си
Сокеты в Си
К и Р
Что такое argc, char * argv[]
Указатели
Структуры в Си
Запросы к REST API на Си
Оператор «стрелка» указатель на член структуры

Search this site

Subscribe to Telegram channel @aofeed to follow new articles and updates to old ones

Go to channel

@aofeed

Ask a question in the Telegram group

@aofeedchat

Contacts and cooperation:
I recommend our hosting beget.ru
Write to info@urn.su if you:
1. Want to write an article for our site or translate an article into your native language.
2. Want to place thematically relevant ads on the site.
3. Ads on my site pass maximum censorship. If you see an ad block unsuitable for school-age children, shocking or misleading - please contact us by e-mail
4. Found a mistake, inaccuracy, bug, etc. on the site. ... .......
5. Articles can be shared on social media by clicking a network icon: