问题描述
程序测试
隐式无
字符(LEN = 100)::输入
字符(LEN = 100)::输出
print *,请输入您的信息:
read *,输入
对于每个角色,我都使用Ceaser的密码进行加密。
计算
<$ p $ print *,这是输出:
write(*,(2a))Message =,out
end program Test
这完全不起作用。
对于输入中的每个字符,我使用模(iachar())函数对其进行转换。它的工作直到打印,我跟着调试,加密是好的。
但是输出的问题在于LEN = 100。 do循环将经过100次将不存在的字符转换为垃圾,在输出时使用UNDEFINED TYPE打破程序。
read语句应该填充 input
out到空白变量的全长(100个字符),而不是添加垃圾。 LEN_TRIM内部函数将给出变量值的显着长度 - 即不包括尾随空白的长度。您可能需要记住输出字符串的重要长度,以便在打印输出字符串时使用。
(请注意列表引导输入的规则(由*中的*表示)阅读语句)可能有点令人惊讶 - (A)的格式可能更强大,取决于您想要的行为。)
在避免固定在读取输入的上下文中的长度字符串 - Fortran 2003引入了延迟长度字符,这在这里很有帮助。否则,请参阅,了解Fortran 95的可能性。其中一个复杂因素是您正在从控制台读取数据,因此退格语句可能不起作用。解决此问题的方法遵循与链接相似的方法,但需要在输入记录长度正在确定的同时,将输入字符串分段构建为可分配的字符数组。然后使用序列关联将该数组转换为正确长度的标量。如果您想了解更多详情,请留言或询问。
program Test
implicit none
character (LEN=100) :: input
character (LEN=100) :: output
print *,"Please input your message: "
read *, input
For every character, I encrypt it in Ceaser's Cipher
Calculations
print *,"This is the output: "
write (*,"(2a)") "Message = ", out
end program Test
This doesn't work entirely.
For every character in the input, I convert it using the modulo(iachar()) functions. It works up until the print, I followed the debugging, the encryption is fine.But the issue with the output lies in LEN=100. The do loop will go through 100 times converting nonexistent characters into garbage, breaking the program at output with UNDEFINED TYPE.
So if I input "test", it will encrypt CBNC*GARBAGE-TO-100* and not output. If I define length as 4, and do it, it works. but I want to be able to do it without defining a length. Any way around this?
The read statement should pad input
out to the full length of the variable (100 characters) with blanks, rather than adding "garbage". The LEN_TRIM intrinsic function will give the significant length of the variable's value - i.e. the length excluding trailing blanks. You may need to remember this significant length of the input string for when you print the output string.
(Note the rules on list directed input (indicated by the * in the read statement) can be a little surprising - a format of "(A)" may be more robust, depending on the behaviour your want.)
In terms of avoiding fixed length strings in the context of reading input - Fortran 2003 introduces deferred length character, which greatly helps here. Otherwise see Reading a character string of unknown length for Fortran 95 possibilities. One complication is that you are reading from the console, so the backspace statement may not work. The work around to that follows a similar approach to that linked, but necessitates piecewise building the input string into an allocatable array of character at the same time as the input record length is being determined. Sequence association is then used to convert that array into a scalar of the right length. Comment or ask again if you want more details.
这篇关于未定义长度的Fortran字符输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!