#toggle the string
#include <stdio.h>
int main()
{
char S[100],ch;
int i=0;
gets(S);
while((S[i]!='\0')&&(i<100))
{
ch=S[i];
if((ch>='A')&&(ch<='Z'))
S[i]+=32;
else if((ch>='a')&&(ch<='z'))
S[i]-=32;
i++;
}
printf("%s\n",S);
return 0;
}
请让我知道代码有什么问题(代码是将字符串即大写字母切换为小写字母,反之亦然。我收到 SIGABRT 运行时错误...
最佳答案
以下建议代码:
- 干净地编译
- 记录了包含每个头文件的原因
- 即使在非 ASCII 字符集(如 EBCDIC)上也能正常工作
- 消除不需要的变量
- 使用有效的函数调用:
fgets()
从标准输入读取 - 要退出此程序,请输入:Ctrl+c 或(取决于操作系统)Ctrl+d 或Ctrl+z
现在是代码:
#include <stdio.h> // fgets(), printf()
#include <ctype.h> // toupper(), tolower(), isupper(), islower()
int main( void )
{
char S[100];
//gets(S);
if( fgets( S, sizeof( S ), stdin ) )
{
for( size_t i=0; S[i]; i++ )
{
if( isupper( S[i]) )
S[i] = (char)tolower( S[i] );
else if( islower( S[i] ) )
S[i] = (char)toupper( S[i] );
}
printf("%s\n",S);
}
return 0;
} // end function: main
关于c - 运行时错误-SIGABRT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44473406/