简体   繁体   English

我没有为我的 C 程序获得确切的 output

[英]i am not getting the exact output for my C program

The problem is: Write a C program to covert lowercase letters to uppercase letters and vice versa of string S. 1<=S<=100问题是:编写一个 C 程序将字符串 S 的小写字母转换为大写字母,反之亦然。 1<=S<=100

EXAMPLE:例子:

INPUT输入

HelloWORLD

Expected OUTPUT预计OUTPUT

hELLOworld

INPUT输入

RanDoM

Expected OUTPUT预计OUTPUT

rANdOm

My code我的代码

#include<stdio.h>
#include<string.h>

int main()
{ char s[100];
int i;
for (int j=0; j<=100 ; j++)
{
 scanf("%s",&s[j]) ;
}
for (i=0; s[i]!='\0'; i++)
    {
        if (s[i]>='a' && s[i]<='z')
        {
            s[i] = s[i] - 32;

        }
        else
        {
            s[i] = s[i] +32;

        }

    }
    for (int k=0; k<=100 ; k++)
    {    
        if (s[k]!='\0')
      {  printf("%c",s[k]) ; }
    }


    return 0;

}

The OUTPUT which I am getting is:我得到的 OUTPUT 是:

INPUT输入

HelloWORLD

Current OUTPUT当前 OUTPUT

hELLOworldԯ@ _�"����ԯ8_�"�>sn�"�

INPUT输入

 RanDoM

Current OUTPUT当前 OUTPUT

rANdOm�
�$@0�������$H����>s�

What changes in the code do I need to make so that I can get rid of the symbols at the end of the word?我需要对代码进行哪些更改才能去掉单词末尾的符号?

After all the suggestions and help I have found the code which gives the expected output:在所有建议和帮助之后,我找到了给出预期 output 的代码:

#include<stdio.h>
    #include<string.h>
    #include<stdlib.h>
    int main()
    {  char str[100];
 scanf("%s",str);
       int i;

    for (i=0; i<sizeof(str); i++)
        {    
            if (str[i]>='a' && str[i]<='z'&& str[i]!='\0')
            {
                str[i] = str[i] - 32;

            }
            else if(str[i]>='A' && str[i]<='Z'&& str[i]!='\0')
            {
                str[i] = str[i] +32;

            }

        } 
         printf("%s",str);
        return 0;

    }

Hi There some extra code in your program and some mistakes also.嗨,您的程序中有一些额外的代码,也有一些错误。 I am doing some correction in your program to complete your task.我正在对您的程序进行一些更正以完成您的任务。

  • I am not writing new code for your better understanding我不是为了您更好地理解而编写新代码
  • I am not removing lines, just commenting those lines and giving reason in line comments我没有删除行,只是评论这些行并在行注释中给出原因
  • You should read all comments and remove before use.您应该阅读所有评论并在使用前删除。
  • For any confusion ask in comment section如有任何困惑,请在评论部分询问

 #include<stdio.h> #include<string.h> int main() { char s[100]; int i,j,k; //Loop not required //for (j=0; j<=100; j++) //{ scanf("%s",&s[j]); //} for (i=0; s[i];= '\0'; i++) { //You should have to compare with ASCII or use string methods like islower //if (s[i]>='a' && s[i]<='z') if (s[i]>= 97 && s[i]<= 122) // ASCII for a-97 and z-122 { s[i] = s[i] - 32; } else //u may put a check here for upper case to handle errors { s[i] = s[i] + 32; } } //No loop or if statement required // for (k=0; k<=100, k++) //{ // if (s[k];='\0') // { printf("%s";s) ; // } //} return 0; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM