string 在 Fortran 中读取带空格的字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6319631/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Reading a string with spaces in Fortran
提问by Gautam
Using read(asterisk, asterisk) in Fortran doesn't seem to work if the string to be read from the user contains spaces. Consider the following code:
如果要从用户读取的字符串包含空格,则在 Fortran 中使用 read(asterisk, asterisk) 似乎不起作用。考虑以下代码:
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? Many thanks!
如果用户输入字符串“Hello, my name is John Doe”,则只有“Hello”将存储在输入中;空格后的所有内容都被忽略。我的假设是编译器假设“Hello”是第一个参数,而“my”是第二个参数,因此要捕获其他单词,我们必须使用 read( ,) input1, input2, input3 之类的东西...等。这种方法的问题是我们需要为每个输入创建大型字符数组,并且需要确切知道将输入多少个单词。有没有办法解决??某些功能实际上会读取整个句子,空格和所有内容?非常感谢!
回答by Rook
character(100) :: line
write(*,'("Enter some text: ",\)')
read(*,'(A)') line
write(*,'(A)') line
end
... 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.
... 将读取一行最大长度为 100 的文本(对于大多数实际用途来说足够了)并将其写回给您。根据自己的喜好修改。
回答by John Zwinck
Instead of read(*, *)
, try read(*, '(a)')
. I'm no Fortran expert, but the second argument to read
is the format specifier (equivalent to the second argument to sscanf
in C). *
there means list format, which you don't want. You can also say a14
if you want to read 14 characters as a string, for example.
而不是read(*, *)
,尝试read(*, '(a)')
。我不是 Fortran 专家,但 to 的第二个参数read
是格式说明符(相当于sscanf
C 中的第二个参数)。 *
有意味着你不想要的列表格式。例如,您还可以说a14
是否要将 14 个字符作为字符串读取。