在 Fortran 中读取带空格的字符串

发布于 2024-11-15 12:59:53 字数 433 浏览 2 评论 0原文

如果要从用户读取的字符串包含空格,则在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

鱼忆七猫命九 2024-11-22 12:59:53
  character(100) :: line

  write(*,'("Enter some text: ",\)')
  read(*,'(A)') line
  write(*,'(A)') line

  end

...将读取最大长度为 100 的一行文本(足以满足大多数实际用途)并将其写回给您。根据您的喜好进行修改。

  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.

小耗子 2024-11-22 12:59:53

不要使用 read(*, *),而是尝试 read(*, '(a)')。我不是 Fortran 专家,但 read 的第二个参数是格式说明符(相当于 C 中 sscanf 的第二个参数)。 * 表示列表格式,这是您不需要的。例如,如果您想将 14 个字符作为字符串读取,您也可以说 a14

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文