我試圖將小寫字母中的字符串轉換爲大寫字母。 我得到了一些錯誤(訪問volation) 什麼?將小寫字母轉換爲大寫字母
int main()
{
char str[10];
int i=0;
scanf("%s", &str);
while (str[i] !=0)
{
str[i] += -32;
printf("%s", str[i]);
}
return 0;
}
THX
我試圖將小寫字母中的字符串轉換爲大寫字母。 我得到了一些錯誤(訪問volation) 什麼?將小寫字母轉換爲大寫字母
int main()
{
char str[10];
int i=0;
scanf("%s", &str);
while (str[i] !=0)
{
str[i] += -32;
printf("%s", str[i]);
}
return 0;
}
THX
int main()
{
char str[10];
int i=0;
scanf("%s", str);
while (str[i] != 0)
{
str[i] += -32;
i++;
}
printf("%s", str);
return 0;
}
,當然,你必須檢查STR的溢出...
如果超過900個字符輸入的字符串長,scanf()
會嘗試寫超過字符串緩衝區的末尾。
你的while循環永遠不會終止,因爲你永遠不會改變i
。
您應該在printf()
調用中使用"%c"
作爲格式字符串,因爲您正在寫字符而不是以空值終止的字符串。
您更好地使用toupper
/* toupper example */
#include <stdio.h>
#include <ctype.h>
int main()
{
int i=0;
char str[]="Test String.\n";
char c;
while (str[i])
{
c=str[i];
putchar (toupper(c));
i++;
}
return 0;
}
這裏有幾個錯誤:
scanf("%s", &str);
- 因爲str是燒焦的指針,你不需要給它的地址,但是scanf("%s", str);
。 (正如sven所說,這是不安全的)while (str[i] !=0)
這是一個無限循環,你應該在while塊的末尾增加i
。str[i] += -32;
將修改任何燒焦你在,你應該檢查這是否是一個小寫的任何時間,例如:
如果(STR [1]> = 'A' & & STR [1] < ='z'){ str [i] - = 32; } //無法格式化此行出於某種原因....
printf("%s", str[i])
再次是用printf走錯了路,因爲%s
預計char*
,並str[i]
是char
。相反,使用printf("%c", str[i])
這需要一個字符
正如cprogrammer說
您更好地使用TOUPPER
/* toupper example */ #include <stdio.h> #include <ctype.h> int main() { int i=0; char str[]="Test String.\n"; char c; while (str[i]) { c=str[i]; putchar (toupper(c)); i++; } return 0; }
但如果沒有,你想要做你的方式
int main()
{
char str[10];
int i=0;
scanf("%s", &str);
while (str[i]!='\0' && i<10)
{// You forgot this: '\0' instead of 0 and also i<10
str[i] += -32;
printf("%c", str[i]);//char, not string
i++; //And this
}
return 0;
}
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main();
{
int i, count;
char str[200];
clrscr();
printf("Enter a string");
scanf("%s", str);
count = strlen(str);
for(i=0; i<=count; i++)
{
if((str[i] >= 97) && (str[i] <= 122))
{
str[i] = str[i] - 32;
}
}
printf("%s", str);
getch();
}
請儘量避免僅用代碼回答,向您的代碼添加一些解釋以獲得更高質量的答案 – Dreen 2012-10-10 18:20:14
您可以使用Bitwise AND(&
)運算符技術將小寫字母改爲大寫字母。
char ch = letter & 223; [letter = a-z] // Now ch is all time capital letter
如果是作業,請標記爲這樣。 – MByD 2011-03-31 13:51:34
除了你的bug,你不會增加我 - >無限循環 – 2011-03-31 13:52:04
沒有保證所有字母在所有系統上都是按順序排列的。我住在哪裏,我們相信åäö是有效的信件。 – 2011-03-31 13:55:48