在 Fortran 中读取带空格的字符串
如果要从用户读取的字符串包含空格,则在 Fortran 中使用 read(*,*)
似乎不起作用。 考虑以下代码:
character(Len = 1000) :: input = ' '
read(*,*) input
如果用户输入字符串“Hello, my name is John Doe”,则只有“Hello,”将存储在输入中;空格之后的所有内容都将被忽略。我的假设是编译器假设“Hello”是第一个参数,“my”是第二个参数,因此要捕获其他单词,我们必须使用类似 read(*,*) input1、input2、input3...
等。这种方法的问题是我们需要为每个输入创建大型字符数组,并且需要确切地知道将输入多少个单词。
有什么办法解决这个问题吗?是否有某个函数能够真正读取整个句子、空格等?
Using read(*,*)
in Fortran doesn't seem to work if the string to be read from the user contains spaces.
Consider the following code:
character(Len = 1000) :: input = ' '
read(*,*) input
If the user enters the string "Hello, my name is John Doe", only "Hello," will be stored in input; everything after the space is disregarded. My assumption is that the compiler assumes that "Hello," is the first argument, and that "my" is the second, so to capture the other words, we'd have to use something like read(*,*) input1, input2, input3...
etc. The problem with this approach is that we'd need to create large character arrays for each input, and need to know exactly how many words will be entered.
Is there any way around this? Some function that will actually read the whole sentence, spaces and all?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
...将读取最大长度为 100 的一行文本(足以满足大多数实际用途)并将其写回给您。根据您的喜好进行修改。
... will read a line of text of maximum length 100 (enough for most practical purposes) and write it out back to you. Modify to your liking.
不要使用
read(*, *)
,而是尝试read(*, '(a)')
。我不是 Fortran 专家,但read
的第二个参数是格式说明符(相当于 C 中sscanf
的第二个参数)。*
表示列表格式,这是您不需要的。例如,如果您想将 14 个字符作为字符串读取,您也可以说a14
。Instead of
read(*, *)
, tryread(*, '(a)')
. I'm no Fortran expert, but the second argument toread
is the format specifier (equivalent to the second argument tosscanf
in C).*
there means list format, which you don't want. You can also saya14
if you want to read 14 characters as a string, for example.