Функция scanf в языке C
Scanf – это процедура ввода общего назначения, позволяющая считывать данные из потока stdin. При помощи её могут считываться данные всех базовых типов языка.
Вызов scanf
Для того, чтобы считать 2 целых числа, вызов scanf происходит следующим образом:
- %d — это спецификатор преобразования, читающий десятичное число
- a и b—переменные, куда записывается считываемое значение.
Ещё один пример вызова scanf:
Здесь помимо спецификаторов %d, также использован символ «:».
Спецификаторы преобразования для функции scanf()
Первым символом в спецификаторах формата ввода является «%». Далее будут рассмотрены некоторые примеры таких спецификаторов:
- %% – Читает знак «%»
- %[] – Производит чтение набора сканируемых символов
- %a – Читает значение с плавающей точкой в шестнадцатеричной системе исчисления
- %c – Производит чтение одиночного символа
- %d – Производит чтение десятичного целого числа (тип int)
- %e, %f, %g – Читают числа с плавающей точкой
- %hd – Считывает короткое целое число (shortint)
- %hhd – Считывает десятичное число и записывает в переменную типа char
- %hhu – Считывает десятичное число без знака и записывает в переменную типа unsignedchar
- %hu – Считывает короткое целое число без знака (unsignedshortint)
- %i – Может читать числа и в десятичном, и в восьмеричном, и в шестнадцатеричном формате
- %lf – Считывается значение типа double
- %Lf – Считывается длинное вещественное число (тип longdouble)
- %n – Принимает значение, которое равное количеству считанных символов
- %о – Считывает число в восьмеричной системе
- %p – Считывает указатель (pointer)
- %s – Считывается последовательность символов без пробелов и записывается в тип char* или char[]
- %u – Производит чтение десятичного целого числа без знака (тип unsignedint)
Отличия scanf() от printf()
В языках Cи C++ есть ещё одна похожая на scanf()функция. Это printf(). Она в отличие от первой не считывает данные с потока stdin, а выводит их на экран в поток stdout. Здесь так же, как и в команде scanf()есть собственные спецификаторы (иначе они называются командами форматирования).
Чем же различаются printf() и scanf()? Кроме разного синтаксиса и того, что первая предназначена для вывода, а вторая – для ввода, можно ещё добавить, что в них ещё различается форма строк и функция scanf() возвращает значение, которое равно количеству считанных и записанных в параметры значений.
Примеры использования функции scanf()
Символ «*» в строке.
Знак «*», находящийся между «%» и спецификатором преобразования, считывает данные указанного типа, но подавляет их присваивание.
Чтение нескольких символов в строке.
Если необходимо считать не более, чем n символов в указанный массив, то можно использовать выражение “%ns”в строке, где n – это максимально допустимое количество считываемых символов.
Здесь вводятся 3 одиночных символа и присваиваются для 3 переменных.
Другие подобные функции в C / C++
Кроме функций printf и scanf в языках C и C++ также существуют и другие функции ввода/вывода.
Cin и cout предназначены для поточного ввода и вывода в языке C++. Для их использования нужно подключить дополнительную библиотеку . Также эти функции находятся в именном пространстве “std”, поэтому нужно либо подключить его в начале приложения, либо прописать перед вызовом самих функций.
Код, приведённый ниже, в итоге даст один и тот же результат для ввода / вывода:
Вывод
В C есть ещё и другие функции ввода / вывода. Среди них getchar()/putchar() и gets()/puts(). При помощи getchar() можно ввести один символ с клавиатуры. C помощью putchar() же можно вывести на консоль один символ. В то время, функции gets() и puts() позволяют ввести либо вывести строку.
Примеры кода с такими функциями
Getchar / putchar:
Код:int a;
a = getchar(); // вводим символ
printf(«%c «, a); // выводим его при помощи функции printf
putchar(a); // выводим её при помощи функции putchar
putchar(‘\n’);Вывод:u // результат вывода, используя printf
uu// результат вывода, используя putchar
Gets / puts:
char name[30];
char *nP;printf(«Введите имя и фамилию: «);
gets(name);// ввод строкиprintf(«Имя: «);
for(nP = name; *nP != ‘ ‘; nP++)
putchar(*nP);printf(«\nФамилия: «);
puts(nP+1);// вывод
Функция ввода / вывода в других языках программирования
Delphi / Pascal
В языках Delphi и Pascal для ввода данных в консоли используются функции read и readln. Первая только вводит текст, а вторая – вводит и вдобавок производит перенос строки. Для вывода текста используются write иwriteln. Окончание ‘ln’здесь значит то же, что и в readln, т.е. перевод на новую строку.
В языке Delphi в оконных приложениях также можно выводить текст при помощи сообщений. Сделать это можно процедурой ShowMessage или функцией MessageDlg. Для ввода же можно использовать InputBox().
Примеры кода:
read(а); // запись readс одной переменной
read(Cena,Kol); //запись readс двумя переменными
readln (а, В) ; // запись readln
write(‘Значение перем’);
write(‘енной:’); // использование функции write
ShowMessage(‘Сообщение’);// вывод в оконных приложениях Delphi№1
r := MessageDlg(“Дискриминант равен нулю’ + #13
+ ‘Уравнение не имеет действительных корней.’, mtInformation, [mbOK], 0);// вывод в оконных приложениях Delphi№2
S := InputBox(‘Фунты-килограммы’, ‘Введите вес в фунтах’, ‘’);// ввод в оконных приложениях Delphi
В C# текст вводится при помощи команд ReadKey и ReadLine, которые считывают соответственно один символ либо целую строку. Выводятся данные командами Write и Writeline.
Примеры кода:
Console.ReadKey();
string name = Console.ReadLine();
Console.Write(«Введите свое имя: «);
Console.WriteLine(«Добро пожаловать в C#!»);
В языке программирования Java для считывания данных используются методы next, nextInt, nextLine и некоторые другие. Метод next() считывает слово или фразу, которое ввёл пользователь, до тех пор пока не будет найден первый пробел.
Метод nextInt() считывает с консоли целое число. Метод nextLine() считывает строку до тех пор, пока не будет нажата клавиша «Enter». Для вывода в Java предназначены методы print, printf и println. Различаются они своим способом передачи информации на экран.
Print – это обычный вывод информации, println – это вывод информации + перенос строки, а printf – это форматированный вывод по аналогии с одноимённой функцией из языка C++. Перед методами вывода записывается выражение «System.out.». Означает оно, что перед вызовом этих методов мы обращаемся к статическому полю out из класса System.
Примеры кода:
String val=sc.next();
int val=sc.nextInt();
String val=sc.nextLine();
System.out.print(«Amigo «);
System.out.println(«is the best!»);
System.out.printf(«%4d», multiplyTab[i][j]);
Python
Чтобы ввести данные в языке Python используется функция input(). Для вывода данных используется функция print().
Scanf c что это
Для ввода данных в консоли может использоваться функция scanf() . Эта функция определена в заголовочном файле stdio.h (там же, где и функция printf) и имеет следующее формальное определение:
И форматная_строка, и аргументы для функции scanf обязательны.
Форматная_строка содержит спецификации преобразования, которые определяют вводимые данные. Общий вид спецификаций преобразования:
Из этих элементов обязательны только два: знак процента % и спецификатор.
Спецификатор определяет тип вводимых данных:
%c : считывает один символ
%d : считывает десятичное целое число
%i : считывает целое число в любой системе (десятичной, шестнадцатеричной, восьмеричной)
%u : считывает положительное целое число
%e : считывает число с плавающей точкой в экспоненциальной форме
%E : считывает число с плавающей точкой в экспоненциальной форме с заглавным символом экспоненты
%f : считывает число с плавающей точкой
%F : считывает число с плавающей точкой
%g : считывает число с плавающей точкой
%G : считывает число с плавающей точкой
%o : считывает восьмеричное число
%x : считывает шестнадцатеричное число
%X : считывает шестнадцатеричное число
%s : считывает строку
%% : считывает символ процента
Символ звездочки * в спецификации преобразования позволяет пропустить при вводе водимые символы для типа, указанного через спецификатор.
Ширина_поля представляет целое положительное число, которое позволяет определить, какое количество байтов будет учитываться при вводе.
Модификаторы позволяют конкретизировать тип данных. В частности, есть следующие модификаторы:
h : для ввода значений типа short int ( %hd )
l : для ввода значений типа long int ( %ld ) или double ( %lf , %le )
L : для ввода значений типа long double ( %Lf , %Le )
В качестве аргументов в функцию scanf() передаются адреса переменной, которая будет получать введенное значение. Для получения адреса переменной перед ее именем ставится знак амперсанда & . Например, если переменная называется age , то ее адрес мы можем получить с помощью выражения &age .
Например, введем с консоли числовое значение:
Здесь вводится значение для переменной age, которая представляет тип int , поэтому в форматную строку в функции scanf передается спецификатор %d . Здесь не используется ни символ звездочки, ни ширина поля, ни модификаторы. Вторым параметром идет адрес переменной age — &age .
После ввода значения мы можем его использовать, например, вывести на консоль:
Аналогичен будет ввод данных других типов:
После ввода значения мы можем его использовать, например, вывести на консоль:
Можно сразу вводить несколько значений. В этом случае в качестве разделителя используется пробел:
При вводе данных в консоли функция scanf может использовать пробелы в качестве разделителей, чтобы выдернуть из ввода значения для определенных переменных. Консольный ввод-вывод:
Ввод строк
Функция scanf() также позволяет вводить строки. Например:
Здесь для имени выделяется 10 символов. Теоретически мы можем ввести и большее количество символов, но чтобы только 10 из них учитывались, в строку форматирования передается ширина поля, которая представляет 10 символов — %10s . Когда функция считает достаточное количетсво символов, она прекратит считывание.
Обратите внимание, что для ввода строки перед названием переменной не указывается символ адреса.
Потому что название массива уже само по себе представляет адрес на первый элемент массива.
Возможный консольный вывод:
Однако при использовании этой функции мы можем столкнуться с рядом проблем. Прежде всего попробуйте ввести в предыдущем примере составное имя, в которм подстроки разделены пробелами, например, «Tom Smith».
Для решения этой проблемы можно использовать один хак:
Спецификатор %10[^\n] указавает, что мы по прежнему считываем неболее 10 символов. Квадратные скобки [] представляют позволяют определить набор символов, которые будут извлекаться из ввода или, наоборот, игнорироваться. Так, выражение [^\n] говорит, что надо считать ввод до тех пор пока не встретиться символ перевода строки ‘\n’, то есть пока пользователь не нажмет на клавишу Enter.
Функция scanf() в СИ: определение, примеры, применение, таблица
В функциональности этих функций нет никакой разницы, просто scanf() появилась в первых версиях языка С, поэтому считается менее защищенной. Обычно при работе с о scanf() в современных компиляторах требуется наличие строки «#define _CRT_SECURE_NO_WARNINGS» в кодовом документе.
Либо можно применять усовершенствованную функцию scanf_s(), которая считается уже защищенной и не требует наличия вышеописанной строки.
Заключение
В программах информация не только выводится, но и принимается. Теперь вы знаете, что при помощи функции scanf() в Си можно принять любые данные, главное — правильно обозначить спецификатор. Немного потренировавшись, вы поймете , что с функцией «сканф» в Си работать не сложнее , чем с функцией printf() в этом же языке.
Мы будем очень благодарны
если под понравившемся материалом Вы нажмёте одну из кнопок социальных сетей и поделитесь с друзьями.
scanf()
The scanf() function scans input from the file designated by stdin under control of the argument format. The format string is described below. Following the format string is the list of addresses of items to receive values.
Format control string
The format control string consists of zero or more format directives that specify acceptable input file data. Subsequent arguments are pointers to various types of objects that are assigned values as the format string is processed.
A format directive can be a sequence of one or more white-space characters, an ordinary character, or a conversion specifier:
- An ordinary character in the format string is any character, other than a white-space character or the percent character (%), that is not part of a conversion specifier.
- A conversion specifier is a sequence of characters in the format string that begins with a percent character (%) and is followed, in sequence, by the following:
- an optional assignment suppression indicator: the asterisk character (*)
- an optional decimal integer that specifies the maximum field width to be scanned for the conversion
- an optional pointer-type specification: one of N or F
- an optional type length specification: one of h, l, or L
- a character that specifies the type of conversion to be performed: one of the characters cdefginopsux[
As each format directive in the format string is processed, the directive may successfully complete, fail because of a lack of input data, or fail because of a matching error as defined by the particular directive:
- If end-of-file is encountered on the input data before any characters that match the current directive have been processed (other than leading white-space where permitted), the directive fails for lack of data.
- If end-of-file occurs after a matching character has been processed, the directive is completed (unless a matching error occurs), and the function returns without processing the next directive.
- If a directive fails because of an input character mismatch, the character is left unread in the input stream.
Trailing white-space characters, including newline characters, are not read unless matched by a directive. When a format directive fails, or the end of the format string is encountered, the scanning is completed, and the function returns.
When one or more white-space characters (space, horizontal tab \t, vertical tab \v, form feed \f, carriage return \r, new line or linefeed \n) occur in the format string, input data up to the first non-whitespace character is read, or until no more data remains. If no white-space characters are found in the input data, the scanning is complete, and the function returns.
An ordinary character in the format string is expected to match the same character in the input stream.
Conversion specifiers
A conversion specifier in the format string is processed as follows:
- For conversion types other than [, c, and n, leading white-space characters are skipped.
- For conversion types other than n, all input characters, up to any specified maximum field length, that can be matched by the conversion type are read and converted to the appropriate type of value; the character immediately following the last character to be matched is left unread; if no characters are matched, the format directive fails.
- Unless the assignment suppression indicator (*) was specified, the result of the conversion is assigned to the object pointed to by the next unused argument (if assignment suppression was specified, no argument is skipped); the arguments must correspond in number, type and order to the conversion specifiers in the format string.
Pointer-type specifications
A pointer-type specification is used to indicate the type of pointer used to locate the next argument to be scanned:
F pointer is a far pointer N pointer is a near pointer
The pointer type defaults to that used for data in the memory model for which the program has been compiled.
Type length specifiers
A type length specifier affects the conversion as follows:
- h causes a d, i, o, u or x (integer) conversion to assign the converted value to an object of type short int or unsigned short int.
- h causes an f conversion to assign a fixed-point number to an object of type long consisting of a 16-bit signed integer part and a 16-bit fractional part. The integer part is in the high 16 bits and the fractional part is in the low 16 bits.
- h causes an n (read length assignment) operation to assign the number of characters that have been read to an object of type unsigned short int.
- h causes an s operation to convert the input string to an ASCII character string. For scanf(), this specifier is redundant.
- l causes a d, i, o, u or x (integer) conversion to assign the converted value to an object of type long int or unsigned long int.
- l causes an n (read length assignment) operation to assign the number of characters that have been read to an object of type unsigned long int.
- l causes an e, f or g (floating-point) conversion to assign the converted value to an object of type double.
Conversion type specifiers
The valid conversion type specifiers are:
c Any sequence of characters in the input stream of the length specified by the field width, or a single character if no field width is specified, is matched. The argument is assumed to point to the first element of a character array of sufficient size to contain the sequence, without a terminating null character ('\0'). For a single character assignment, a pointer to a single object of type char is sufficient. d A decimal integer, consisting of an optional sign, followed by one or more decimal digits, is matched. The argument is assumed to point to an object of type int. e, f, g A floating-point number, consisting of an optional sign (+ or -), followed by one or more decimal digits, optionally containing a decimal-point character, followed by an optional exponent of the form e or E, an optional sign and one or more decimal digits, is matched. The exponent, if present, specifies the power of ten by which the decimal fraction is multiplied. The argument is assumed to point to an object of type float. i An optional sign, followed by an octal, decimal or hexadecimal constant is matched. An octal constant consists of 0 and zero or more octal digits. A decimal constant consists of a nonzero decimal digit and zero or more decimal digits. A hexadecimal constant consists of the characters 0x or 0X followed by one or more (upper- or lowercase) hexadecimal digits. The argument is assumed to point to an object of type int. n No input data is processed. Instead, the number of characters that have already been read is assigned to the object of type unsigned int that is pointed to by the argument. The number of items that have been scanned and assigned (the return value) is not affected by the n conversion type specifier. o An octal integer, consisting of an optional sign, followed by one or more (zero or nonzero) octal digits, is matched. The argument is assumed to point to an object of type int. p A hexadecimal integer, as described for x conversions below, is matched. The converted value is further converted to a value of type void* and then assigned to the object pointed to by the argument. s A sequence of non-whitespace characters is matched. The argument is assumed to point to the first element of a character array of sufficient size to contain the sequence and a terminating null character, which is added by the conversion operation. u An unsigned decimal integer, consisting of one or more decimal digits, is matched. The argument is assumed to point to an object of type unsigned int. x A hexadecimal integer, consisting of an optional sign, followed by an optional prefix 0x or 0X, followed by one or more (upper- or lowercase) hexadecimal digits, is matched. The argument is assumed to point to an object of type int. [c1c2. ] The longest, nonempty sequence of characters, consisting of any of the characters c1, c2, . called the scanset, in any order, is matched. The first character, c1 cannot be the caret character ('^'). If c1 is ], that character is considered to be part of the scanset and a second ] is required to end the format directive. The argument is assumed to point to the first element of a character array of sufficient size to contain the sequence and a terminating null character, which is added by the conversion operation.
A dash (-) in the scanset doesn’t indicate a range of characters. For example, the string [0-9] matches the characters 0, -, and 9, not the characters 0 through 9. [^c1c2. ] The longest, nonempty sequence of characters, consisting of any characters other than the characters between the ^ and ], is matched. As with the preceding conversion, if c1 is ], it is considered to be part of the scanset, and a second ] ends the format directive. The argument is assumed to point to the first element of a character array of sufficient size to contain the sequence and a terminating null character, which is added by the conversion operation.
For example, the specification %[^\n] will match an entire input line, up to but not including the newline character.
A dash (-) in the scanset doesn’t indicate a range of characters. For example, the string [^0-9] matches characters other than 0, -, and 9, not characters other than 0 through 9. A conversion type specifier of % is treated as a single ordinary character that matches a single % character in the input data. A conversion type specifier other than those listed above causes scanning to terminate, and the function to return.
will copy "some_string" into the array name, skip 34.555e-3, assign 0xabc to hexnum and 1234 to decnum. The return value will be 3.
will assign "They may look alike" to string1, skip the comma (the "%*2s" will match only the comma; the following blank terminates that field), and assign " but they don't perform alike." to string2.
Returns:
The scanf() function returns EOF when the scanning is terminated by reaching the end of the input stream. Otherwise, the number of input arguments for which values were successfully scanned and stored is returned.