[英]C Programme has stopped working while uppercase the Word
此代碼沒有返回大寫單詞,而是停止工作。這是代碼。我在哪里犯了錯誤?
char Uppercase(char country[]){
int i;
for(i=0;i<100;i++){
if(country[i]>=97 && country[i]<=122){
country[i] = 'A'+(country[i]-'a');
}
}
return country;
}
int main(){
char country[100];
printf("Enter The Country Name: ");
scanf("%s",country);
char x = Uppercase(country);
printf("Uppercase is: %s",x);
}
您將變量x
聲明為具有類型char
並嘗試使用為 output 字符串而不是單個字符設計的轉換說明符%s
對其進行 output 。
char x = Uppercase(country);
printf("Uppercase is: %s",x);
這會導致未定義的行為。
以及 function Uppercase
的返回類型char
char Uppercase(char country[]){
int i;
for(i=0;i<100;i++){
if(country[i]>=97 && country[i]<=122){
country[i] = 'A'+(country[i]-'a');
}
}
return country;
}
沒有意義。 此外,編譯器應該為此返回語句發出消息
return country;
function 的返回類型必須是指針類型char *
。
這個for循環也有神奇的數字100
for(i=0;i<100;i++){
沒有意義。 傳遞的數組可以有一個包含比100
少得多的字符的字符串。
並且使用像97
和122
這樣的幻數會使代碼不可讀且容易出錯。
if(country[i]>=97 && country[i]<=122){
至少你可以寫
if(country[i] >= 'a' && country[i] <= 'z'){
例如,function 可以通過以下方式定義
#include <ctype.h>
//...
char * Uppercase( char country[] )
{
for ( char *s = country; *s; ++s )
{
*s = toupper( ( unsigned char ) *s );
}
return country;
}
更好地使用標准函數而不是幻數:
char *strtoupper(char *str)
{
char *wrk = str;
while(*str)
{
*str = toupper((unsigned char)*str);
str++;
}
return wrk;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.