使用sprintf和sscanf,

时间:2019-05-31 07:32:04

标签: c++ c

我正在尝试将给定整数中的所有0替换为5。

为此,我正在使用sprintf将整数转换为字符串并对字符串进行操作,最后将字符串转换回整数

下面是代码:

#include<stdio.h>

int main() {

    int num=0, i=0;
    char str[10];

    printf("Enter the number: ");
    scanf("%d",&num);

    sprintf(str,"%d",num);
    printf("string str:%s",str);
    while(str[i]!='\0')
    {
        if(str[i]==0)
            str[i]=5;
        i++;
    }

    sscanf(str,"%d",&num);

    printf("\nBefore replacement: %s", str);
    printf("\nAfter replacement: %d", num);

}

我的输出错误

有人可以识别并纠正这里的问题。谢谢:)

3 个答案:

答案 0 :(得分:5)

scanf("%d", num);应该是scanf("%d", &num);

另外,这里

if (str[i] == 0)
    str[i] = 5;

应该是

if (str[i] == '0')
    str[i] = '5';

因为0'\0'相同,但是您要替换代表0的字符。

此外,在您的输出中,您在混合前后也有混淆。

答案 1 :(得分:2)

    if(str[i]==0)
        str[i]=5;

必须

    if(str[i]=='0')
        str[i]='5';

我还建议您检查初始 scanf 返回1以了解用户是否输入了有效输入

printf("\nBefore replacement: %s", str);
printf("\nAfter replacement: %d", num);

最后产生\ n

printf("Before replacement: %s\n", str);
printf("After replacement: %d\n", num);

,但请注意,您要在替换项之后而不是 before 之前写一个字符串 after ,您必须将case before 放在之前, 或只是删除它,因为您已经在替换之前写了该字符串

示例:

#include<stdio.h>

int main() {

    int num=0, i=0;
    char str[10];

    printf("Enter the number: ");
    if (scanf("%d",&num) != 1)
      puts("invalid input");
    else {
      sprintf(str,"%d",num);
      printf("string str:%s\n",str);
      while(str[i]!='\0')
      {
        if(str[i]=='0')
          str[i]='5';
        i++;
      }

      sscanf(str,"%d",&num);

      printf("After replacement: %d\n", num);
    }

    return 0;
}

编译和执行:

pi@raspberrypi:/tmp $ gcc -pedantic -Wall -Wextra c.c
pi@raspberrypi:/tmp $ ./a.out
Enter the number: aze
invalid input
pi@raspberrypi:/tmp $ ./a.out
Enter the number: 10204
string str:10204
After replacement: 15254
pi@raspberrypi:/tmp $ 

答案 2 :(得分:0)

git