我試圖在Fortran中創建toUpper和toLower函數,並且它們似乎在我的實現中工作正常;程序會提示用戶輸入一個字符串,然後用大寫字母打印出來,然後用小寫字母打印出來。爲什麼我的程序循環兩次?
但是,在我添加一個大寫函數後,程序會提示用戶輸入兩次字符串,但我找不到原因。它似乎工作,但它做了兩次。
有人可以這樣好讓我知道爲什麼我的程序提示輸入兩次?代碼和輸出如下。
program stringutils
character :: words*1000
print*, 'Enter a string.'
read(*,'(A)') words
call toUpper(words)
print*, 'toUpper: ', trim(words)
call toLower(words)
print*, 'toLower: ', trim(words)
call capitalize(words)
print*, 'capitalize: ', trim(words)
end program stringutils
subroutine toUpper(string)
character :: string*1000
integer :: i, charNum
do i = 1, len(trim(string))
charNum = iachar(string(i:i))
if (charNum >= 97 .and. charNum <= 122) then
string(i:i) = achar(charNum - 32)
end if
end do
end subroutine toUpper
subroutine toLower(string)
character :: string*1000
integer :: i, charNum
do i = 1, len(trim(string))
charNum = iachar(string(i:i))
if (charNum >= 65 .and. charNum <= 90) then
string(i:i) = achar(charNum + 32)
end if
end do
end subroutine toLower
subroutine capitalize(string)
character :: string*1000
integer :: i
call toUpper(string(1:1))
do i = 2, len(trim(string))
if (iachar(string(i-1:i-1))==32) then
call toUpper(string(i:i))
else
call toLower(string(i:i))
end if
end do
end subroutine capitalize
輸出示例:
Enter a string.
this IS a tEsT!
toUpper: THIS IS A TEST!
toLower: this is a test!
capitalize: This Is A Test!
Enter a string.
why is this running a second time?
toUpper: WHY IS THIS RUNNING A SECOND TIME?
toLower: why is this running a second time?
capitalize: Why Is This Running A Second Time?
我在Windows中使用gfortran通過MinGW的。
我將子例程轉換爲函數並使用假定的長度字符,但無法編譯。通過靜止的參數具有1000的長度... \t字符(*)FUNCTION TOUPPER(STRING) \t \t字符(*)STRING \t \t整數i \t \t \t DO \t I = 1,LEN (TRIM(STRING)) \t \t \t STRING(I:I)= CHARTOUPPER(STRING(I:I)) \t \t END DO \t END FUNCTION TOUPPER 錯誤:(1)處的字符值內部函數'toupper'不能被假定爲長度。 對不起,我不知道如何格式化。 – nullChar
不要在評論中提問,他們太難閱讀了。 –