📜  fortran int 到字符串 - Fortran (1)

📅  最后修改于: 2023-12-03 15:15:11.087000             🧑  作者: Mango

Fortran Int to String - Fortran

Fortran is a high-level programming language used primarily for scientific and numerical computations. In this tutorial, we will learn how to convert an integer to a string in Fortran.

Approach

To convert an integer to a string in Fortran, we can make use of the write statement with the format specifier. The write statement is normally used to write data to an output file, but it can also be used to format data into a string.

The general syntax of the write statement for converting an integer to a string is as follows:

write(character_variable, '(I0)') integer_variable

Here, character_variable is the variable that will store the converted string, and integer_variable is the integer that needs to be converted.

The (I0) format specifier is used to convert the integer to a string without any leading or trailing spaces.

Example

Here's an example program that demonstrates how to convert an integer to a string in Fortran:

program int_to_string_example
    implicit none
    
    integer :: int_variable
    character(len=15) :: string_variable
    
    int_variable = 12345
    
    write(string_variable, '(I0)') int_variable
    
    print *, "Integer:", int_variable
    print *, "String :", string_variable
    
end program int_to_string_example

In this example, we declare an integer variable int_variable and a character variable string_variable with a length of 15. We assign a value of 12345 to int_variable.

Next, we use the write statement to convert int_variable to a string and store it in string_variable using the (I0) format specifier.

Finally, we print the original integer value and the converted string.

Output

Running the above program will give the following output:

Integer: 12345
String : 12345

As you can see, the integer value 12345 has been successfully converted to a string "12345".

Conclusion

In this tutorial, we have learned how to convert an integer to a string in Fortran using the write statement with the (I0) format specifier. This technique can be useful when you need to convert numerical data to strings for further processing or for displaying the data in a desired format.