Ошибка выполнения 106 турбо паскаль

grand777

23 / 0 / 0

Регистрация: 14.01.2014

Сообщений: 3

1

14.01.2014, 20:19. Показов 5085. Ответов 5

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

Pascal
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
type mas1=array[1..100] of integer;
var a:char; m1,m2,m3:mas1; f1,f2:text; n:byte; i,b:integer;
 
begin
 
assign (f1, 'printer.in');
assign (f2, 'printer.out');
reset (f1);
rewrite (f2);
 
readln (f1, n);
 
 for i:=1 to n do
 begin
 readln (f1, a);
 m1[i]:=ord(a);
 read (f1, m2[i]);
 read (f1, m3[i]);
 end;
 
 while not eof (f1) do
 begin
 read (f1,a);
  for i:=1 to n do begin
  if ord(a)=m1[i] then b:=b+m2[i];
  if ord(a)=m1[i]-26 then b:=b+m3[i]
  end;
 end;
 
write (f2, b);
 
close (f1);
close (f2);
 
end.

printer.in

Pascal
1
2
3
4
5
6
7
5
p 5 6
t 7 8
y 9 10
a 1 2
e 3 4
Petya

Ошибка выполнения 106 по адресу 0000:011D

Помогите, в чём проблема?



0



Супер-модератор

6146 / 2888 / 1299

Регистрация: 04.03.2013

Сообщений: 5,751

Записей в блоге: 1

14.01.2014, 20:46

2

Подпрограммы Read и ReadLn сообщают об этой ошибке, если числовое значение, считанное из текстового файла не соответствует нужному числовому формату.

Проверьте, каждый символ файла printer.in для начала



1



23 / 0 / 0

Регистрация: 14.01.2014

Сообщений: 3

14.01.2014, 21:33

 [ТС]

3

Цитата
Сообщение от ildwine
Посмотреть сообщение

Подпрограммы Read и ReadLn сообщают об этой ошибке, если числовое значение, считанное из текстового файла не соответствует нужному числовому формату.

Проверьте, каждый символ файла printer.in для начала

прикрепил printer.in к первому посту

скорее всего ошибка в том что сначала читаю а (символ), потом число, хотя может быть и нет.

как исправить, не подскажите?

Добавлено через 39 минут
Проблема решена. Можно закрывать тему.



0



Супер-модератор

6146 / 2888 / 1299

Регистрация: 04.03.2013

Сообщений: 5,751

Записей в блоге: 1

14.01.2014, 21:35

4

grand777, темы не закрываются. Если не трудно, поделитесь решением проблемы с будущими поколениями. Возможно кому-то пригодится…



0



grand777

23 / 0 / 0

Регистрация: 14.01.2014

Сообщений: 3

14.01.2014, 21:50

 [ТС]

5

путём отладки пришел к такому решению: (добавлен ряд 20 и 21, не обязательно a[i], это просто чтобы символы, которые паскаль берёт откуда то (так и не понял откуда) пропустить)

Pascal
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
type mas2=array[1..100] of integer;
type mas1=array[1..100] of char;
var d,c:char; m1,m2,m3:mas2; a:mas1; f1,f2:text; n:byte; i,b,code:integer;
 
begin
 
assign (f1, 'printer.in');
assign (f2, 'printer.out');
reset (f1);
rewrite (f2);
 
readln (f1, n);
 
 for i:=1 to n do
 begin
 read (f1, a[i]);
 m1[i]:=ord(a[i]);
 read (f1, m2[i]);
 read (f1, m3[i]);
 read (f1, a[i]);
 read (f1, a[i]);
 end;
 
 while not eof (f1) do
 begin
 read (f1,d);
  for i:=1 to n do begin
  if ord(d)=m1[i]-32 then b:=b+m3[i];
  if ord(d)=m1[i] then b:=b+m2[i];
  end;
 end;
 
write (f2, b);
 
close (f1);
close (f2);
 
end.



0



958 / 577 / 136

Регистрация: 23.05.2012

Сообщений: 7,364

15.01.2014, 00:48

6

Цитата
Сообщение от grand777
Посмотреть сообщение

так и не понял откуда

В конце каждой строки записаны два управляющих символа #10 и #13 — признак конца строки и воззврат каретки. Т.к. чтение было посимвольным, то эти символы Вы тоже читаете.
Кстати, можете, например, в Notepad++ открыть текстовый файл и посмотреть скрытые символы



0



Регистрация   Войти‘;

Авторизация

Логин:

Пароль:

Запомнить меня на этом копьютере

Регистрация
Забыли свой пароль?

  

Справочник |Библиотека |Файлы и загрузки |Уроки |FAQ| Скачать Turbo Pascal Форум

  • Синтаксис языка
  • Типы данных
  • Стандартные модули
  • Процедуры и функции
  • Зарезервированные слова
  • Директивы компилятора
  • Сообщения об ошибках
    • Ошибки выполнения
    • Ошибки компиляции
  • Примеры программ
  • Описание среды разработки

Главная / Справочник / Сообщения об ошибках / Ошибки выполнения

Недопустимый числовой формат.

Описание

Подпрограммы Read и ReadLn сообщают об этой ошибке, если числовое значение, считанное из текстового файла не соответствует нужному числовому формату.

© 2009–2023 Russian Pascal Developer Network.
Техническая площадка: ISBIZ Хостинг

ISBIZ.agency
продвижение сайта

Member Avatar


ddanbe

2,724



Professional Procrastinator



Featured Poster


5 Years Ago

Could you tell me what error 106 means and where in your code it occurs?

Member Avatar


Schol-R-LEA

1,446



Commie Mutant Traitor



Featured Poster


5 Years Ago

As DDanbe said, we’d need to know what ‘error 106’ meant here. However, I think we can elaborate on that to make something of a teachable moment.

First, before I address that, I will point out to you that when you post code samples here, you need to indent every line of the code by at least four spaces, or the formatting won’t be preserved. I suggest reading the docs for the Daniweb version of Markdown for a more detailed explanation.

With that out of the way, let’s get on with the show.

While it isn’t entirely clear without more context, it is safe to guess that the ‘106 error’ is a compiler error message, that is, a report of a problem in the code that indicates a fatal error — something that prevents the compiler from finishing the compilation.

It also could be a compiler warning, which indicates something that could be a mistake, but isn’t serious enough to be a showstopper — something which the compiler isn’t sure is a problem, but thinks you should look into. Or, since you didn’t say when it comes up, it could even be an error message that you get after it is compiled, when the program is running.

But the safe bet is that it is a compiler error message.

This means we’d need to know which compiler you are using. Different compilers — even for the same language — will have different error and warning messages and codes, so we’d have to know where to look the error up in order to figure it out.

There are several Pascal compilers around, the most notable being Delphi, FreePascal, and Gnu Pascal .

Now, Delphi is actually an Integrated Development Environment (IDE) for Object Pascal, which is a different language derived from Pascal, but the Delphi compiler will compile most Standard Pascal code as well, and is sometimes used in courses that teach Pascal (in the same way C++ compilers often double as C compilers). However, the Delphi compiler is a commercial product, so most people have shifted to using the mostly-compatible FreePascal instead.

As the name implies, FreePascal is a free, open-source compiler for Pascal and Object Pascal. It isn’t as refined as Delphi, but it is pretty close, and the limited market interest in Pascal in general means it is a lot more appealing to most people than Delphi. It is often paired with Lazarus IDE, an IDE which emulated the tools found in earlier versions of Delphi.

Gnu Pascal is a part of the Gnu Compiler Collection, being a front-end for the same code generators used by gcc and g++. It isn’t as commonly used as FreePascal, for a variety of reasons, but it is there. It is sometimes used with the Dev-Pascal IDE, but like with all GNU packages, it is really aimed at being used with a general-purpose programmer’s editor such as vim or EMACS.

So, we will need to know which compiler gives an ‘error 106’ message in order to figure this out. Presumably, you know what compiler — or at least what IDE — you are using, so that’s what you would need to tell us.

It would also help if you could tell us the error message itself, and if possible, what part of the code it is pointing to. If you could copy and paste the error message (or make a screen shot of it, though getting the text would be preferable), it should give us a better idea of what it is trying to tell you.

Doing a search on the error message would make sense too, but without knowing the compiler, it might be of limited use. So, Let Me Google That For You, and see what it gives us.

/me reads search results OK, it seems to be a FreePascal ‘invalid numeric format’ error. Oh, it could be some ancient version of Turbo Pascal with a ‘string expression expected’ error, but honestly, if your professor has you using an MS-DOS compiler from thirty years ago, the only solution is to get the other students together, walk out of the course en masse, and complain to the Dean of the university about the incompetent who is teaching the class.

That’s about as much as we really can say, without more information. We could make some guesses, but that’s all they would be, so it would be better if we refrain from that.

Hopefully, this post has taught you a few important lessons about doing the necessary research on your own before asking for help, and providing enough information when you do ask for help. Good luck with that, because no one here is going to give you this much hand-holding ever again.

Edited

5 Years Ago
by Schol-R-LEA because:

clarification re: GCC

Member Avatar


rproffitt

2,424



«Nothing to see here.»



Moderator


5 Years Ago

106 Invalid numeric format

Since we don’t know what you typed in response to each question it appears your code is what we call fragile. Blows up when you input a numeric but answer with a character.

Member Avatar

1 Year Ago

Screenshot_2022-01-17_225355.png

what is this error?
please answer soon!

Member Avatar


Schol-R-LEA

1,446



Commie Mutant Traitor



Featured Poster


1 Year Ago

As Rproffitt said, please make your own new threads rather than resurrecting long-dead ones.

As for the error code, that was explained in detail earlier in this thread: it indicates that you tried to read a number from a file, and got something other than a number, as defined here. The likely solution is to add a check for an end-of-file in the loop, using the function eof().

Though from the screenshot, you might be using Turbo Pascal, where the error indicates a malformed string. The correct solution to this is Don’t Use Turbo Pascal.

Edited

1 Year Ago
by Schol-R-LEA

I’m still fairly new to Pascal and I’m getting these errors and I’m not sure why. Some help would be greatly appreciated.

Runtime error 106 at $004015DFF
                     $004015DF
                     $004016D2
                     $004016FD
                     $004078D1

This is my code if you guys want to take a look.

program BasicReadWrite;

type
  ArrayOfPersons = record
    name: String;
    age: String; 
  end;

procedure WriteLinesToFile(var myFile: TextFile);
begin
  WriteLn(myFile, 5);
  WriteLn(myFile, 'Fred Smith');
  WriteLn(myFile, 28);
  WriteLn(myFile, 'Jill Jones');
  WriteLn(myFile, 54);
  WriteLn(myFile, 'John Doe');
  WriteLn(myFile, 15);
  WriteLn(myFile, 'Samantha Pritchard');
  WriteLn(myFile, 19);
  WriteLn(myFile, 'Hans Fredrickson');
  WriteLn(myFile, 77);
end;

procedure PrintRecordsToTerminal(personArray: ArrayOfPersons; count: 
  Integer);
begin
  WriteLn('Person name: ', personArray.name);
  WriteLn('Age: ', personArray.age);
end;

procedure ReadLinesFromFile(var myFile: TextFile);
var 
  p: ArrayOfPersons;
  number: Integer;
begin
  number := 0;
  while number <= 19 do
  begin
    ReadLn(myFile, number);
    ReadLn(myFile, p.name[number]);
    ReadLn(myFile, p.age);
    number := number + 1;
  end;
end;

1 Out of memory (Выход за границы памяти). 2 Identifier expected (Не указан идентификатор). 3 Unknown identifier (Неизвестный идентификатор). 4 Duplicate identifier (Двойной идентификатор). 5 Syntax error (Синтаксическая ошибка). 6 Error in real constant (Ошибка в вещественной константе). 7 Error in integer constant (Ошибка в целой константе). 8 String constant exceeds line (Строковая константа превышает допустимые размеры). 9 Too many nested files (Слишком много вложенных файлов). 10 Unexpected end of file (He найден конец файла). 11 Line too long (Слишком длинная строка) 12 Type identifier expected (Здесь нужен идентификатор типа). 13 Too many open files (Слишком много открытых файлов). 14 Invalid file name (Неверное имя файла). 15 File not found (Файл не найден). 16 Disk full (Диск заполнен). 17 Invalid compiler directive (Неправильная директива компилятора). 18 Too many files (Слишком много файлов). 19 Undefined type in pointer definition (Неопределенный тип в объявлении указателя). 20 Variable identifier expected (Отсутствует идентификатор переменной). 21 Error in type (Ошибка в объявлении типа). 22 Structure too large (Слишком большая структура). 23 Set base type of range (Базовый тип множества нарушает границы). 24 File components may not be files (Компонентами файла не могут быть файлы) . 25 Invalid string length (Неверная длина строки). 26 Type mismatch (Несоответствие типов). 27 Invalid subrange base type (Неправильный базовый тип для типа-диапазона). 28 Lower bound greater than upper bound (Нижняя граница больше верхней). 29 Ordinal type expected (Нужен порядковый тип). 30 Integer constant expected (Нужна целая константа). 31 Constant expected (Нужна константа). 32 Integer or real constant expected (Нужна целая или вещественная константа) . 33 Type identifier expected (Нужен идентификатор типа) 34 Invalid function result type (Неправильный тип результата функции) 35 Label identifier expected (Нужен идентификатор метки). 36 BEGIN expected (Нужен BEGIN). 37 END expected (Нужен END). 38 Integer expression expected (Нужно выражение типа INTEGER). 39 Ordinal expression expected (Нужно выражение перечисляемого типа). 40 Boolean expression expected (Нужно выражение типа BOOLEAN). 41 Operand types do not match operator (Типы операндов не соответствуют операции). 42 Error in expression (Ошибка в выражении). 43 Illegal assignment (Неверное присваивание). 44 Field identifier expected (Нужен идентификатор поля) . 45 Object file too large (Объектный файл слишком большой). 46 Undefined external (Неопределенная внешняя процедура). 47 Invalid object file record (Неправильная запись объектного файла). 48 Code segment too large (Сегмент кода слишком большой). 49 Data segment too large (Сегмент данных слишком велик). 50 DO expected (Нужен оператор DO). 51 Invalid PUBLIC definition (Неверное PUBLIC-определение). 52 Invalid EXTRN definition (Неправильное EXTRN-определение). 53 Too many EXTRN definition (Слишком много EXTRN-определений). 54 OF expected (Требуется OF). 55 INTERFACE expected (Требуется интерфейсная секция). 56 Invalid relocatable reference (Неправильная перемещаемая ссылка). 57 THEN expected (Требуется THEN). 58 TO or DOWNTO expected (Требуется TO или DOWNTO). 59 Undefined forward (Неопределенное опережающее описание). 60 Too many procedures (Слишком много процедур). 61 Invalid typecast (Неверное преобразование типа). 62 Division by zero (Деление на ноль). 63 Invalid file type (Неверный файловый тип). 64 Cannot Read or Write variables of this type (Нет возможности считать или записать переменные данного типа). 65 Pointer variable expected (Нужно использовать переменную-указатель). 66 String variable expected (Нужна строковая переменная). 67 String expression expected (Нужно выражение строкового типа). 68 Circular unit reference (Перекрестная ссылка модулей). 69 Unit name mismatch (Несоответствие имен программных модулей). 70 Unit version mismatch (Несоответствие версий модулей). 71 Duplicate unit name (Повторное имя программного модуля). 72 Unit file format error (Ошибка формата файла модуля). 73 IMPLEMENTATION expected (Отсутствует исполняемая часть модуля). 74 Constant and case types do not match (Типы констант и тип выражения опе- ратора CASE не соответствуют друг другу). 75 Record variable expected (Нужна переменная типа запись). 76 Constant out of range (Константа нарушает границы). 77 File variable expected (Нужна файловая переменная). 78 Pointer expression expected (Нужно выражение типа указатель). 79 Integer or real expression expected (Нужно выражение вещественного или целого типа). 80 Label not within current block (Метка не находится внутри текущего блока) 81 Label already defined (Метка уже определена). 82 Undefined label in processing statement part (Неопределенная метка в предшествующем разделе операторов). 83 Invalid @ argument (Неправильный аргумент операции @). 84 Unit expected (Нужно кодовое слово UNIT). 85 ”;” expected (Нужно указать”;”). 86 ”:” expected (Нужно указать”:”). 87 ”,”expected (Нужно указать”,”). 88 ”(” expected (Нужно указать ”(”). 89 ”)” expected (Нужно указать”)”). 90 ”=” expected (Нужно указать”=”) 91 ”:=” expected (Нужно указать”:=”) 92 ”[” or ”(.”expected (Нужно указать ”[” или ”(.”). 93 ”]” or ”.)” expected (Нужно указать”]” или ”.)”). 94 ”.” expected (Нужно указать”.”) 95 ”..” expected (Нужно указать”..”). 96 Too many variables (Слишком много переменных). 97 Invalid FOR control variable (Неправильный параметр цикла оператора FOR). 98 Integer variable expected (Нужна переменная целого типа). 99 File and procedure types are not allowed here (Здесь не могут использоваться файлы или процедурные типы). 100 String length mismatch (Несоответствие длины строки). 101 Invalid ordering of fields (Неверный порядок полей). 102 String constant expected (Нужна константа строкового типа). 103 Integer or real variable expected (Нужна переменная типа INTEGER или REAL). 104 Ordinal variable expected (Нужна переменная порядкового типа). 105 INLINE error (Ошибка в операторе INLINE) 106 Character expression expected (Предшествующее выражение должно иметь символьный тип). 107 Too many relocation items (Слишком много перемещаемых элементов). 108 Overflow in arithmetic operator (Переполнение при выполнении арифметического оператора). 109 No enclosing FOR, WHILE or REPEAT statement (Нет операторов, заканчивающих операторы FOR, WHILE или REPEAT). 110 Debug information table overflow (Переполнение информационной таблицы отладки) 111 N/A 112 CASE constant out of range (Константа CASE нарушает допустимые границы) . 113 Error in statement (Ошибка в операторе). 114 114 Cannot call an interrupt procedure (Невозможно вызвать процедуру npерывания). 115 N/A 116 Must be in 8087 mode to compile this (Для компиляции необходим режим 8087). 117 Target address not found (Указанный адрес не найден). 118 118 Include files are not allowed here (Здесь не допускаются включаемые файлы). 119 No inherited methods are accessible here (В этом месте программы нет унаследованных методов). 120 N/A 121 Invalid qualifier (Неверный квалификатор). 122 Invalid variable reference (Недействительная ссылка на переменную). 123 Too many symbols (Слишком много символов). 124 Statement part too large (Слишком большой раздел операторов). 125 N/A 126 Files must be var parameters (Файлы должны передаваться как параметры-переменные). 127 Too many conditional symbols (Слишком много условных символов). 128 Misplaced conditional directive (Пропущена условная директива). 129 ENDIF directive missing (Пропущена директива ENDIF). 130 Error in initial conditional defines (Ошибка в условных определениях). 131 Header does not match previous definition (Заголовок не соответствует предыдущему определению). 132 Critical disk error (Критическая ошибка диска). 133 Cannot evaluate this expression (Нельзя вычислить данное выражение). 134 Expression incorrectly germinated (Некорректное завершение выражения). 135 Invalid format specifier (Неверный спецификатор формата). 136 Invalid indirect reference (Недопустимая косвенная ссылка). 137 Structured variable are not allowed here (Здесь нельзя использовать переменную структурного типа). 138 Cannot evaluate without System unit (Нельзя вычислить выражение без мо-дуля SYSTEM). 139 Cannot access this symbol (Нет доступа к данному символу). 140 Invalid floating-point operation (Недопустимая операция с плавающей запятой). 141 Cannot compile overlay to memory (Нельзя выполнить компиляцию оверлейных модулей в память). 142 Procedure or function variable expected (Должна использоваться перемен- ная процедурного типа). 143 Invalid procedure or function reference (Недопустимая ссылка на процедуру или функцию) . 144 Cannot overlay this unit (Этот модуль не может использоваться в качестве оверлейного). 145 Too many nested scopes (Слишком много вложений). 146 File access denied (Отказано в доступе к файлу). 147 Object type expected (Здесь должен быть тип OBJECT) . 148 object types are not allowed (Нельзя объявлять локальные объекты). 149 VIRTUAL expected (Пропущено слово VIRTUAL). 150 Method identifier expected (Пропущен идентификатор инкапсулированного правила). 151 Virtual constructor are not allowed (Конструктор не может быть виртуальным). 153 Destructor identifier expected (Пропущен идентификатор деструктора). 154 Fail only allowed within constructor (Обращение к стандартной процедуре FAIL может содержаться только в конструкторе). 155 Invalid combination of opcode and operands (Недопустимая комбинация кода команды и операндов). 156 Memory reference expected (Отсутствует адрес). 157 Cannot add or subtract relocatable symbols (Нельзя складывать или вычитать перемещаемые символы). 158 Invalid register combination (Недопустимая комбинация регистров). 159 286/287 instructions are not enabled (Недоступен набор команд микропроцессоров 286/287). 160 Invalid symbol reference (Недопустимая ссылка на символ). 161 Code generation error (Ошибка генерации кода). 162 ASM expected (Отсутствует зарезервированное слово ASM).

Возможно, вам также будет интересно:

  • Ошибка выполнения запроса конфликт блокировок при выполнении транзакции
  • Ошибка выполнения microsoft vbscript что это
  • Ошибка вылетающая при обновлении windows
  • Ошибка выполнения запроса код состояния 302
  • Ошибка выполнения microsoft vbscript невозможно создание объекта контейнером activex

  • Понравилась статья? Поделить с друзьями:
    0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии