有人可以帮助我,告诉我代码有什么问题吗?我使用开关盒制作了解决方案,并将标点符号替换为空字符串。
#include<stdio.h>
#include<string.h>
int main()
{
char st[50];
int i;
printf("ENter the string:\n");
gets(st);
for(i=0;i<strlen(st);i++)
{
switch(st[i])
{
case '!':
case '"':
case '#':
case '$':
case '%':
case '&':strcpy(st[i]," ");
break;
}
printf("String is:\n");
puts(st);
}
return 0;
}
答案 0 :(得分:1)
strcpy(st[i]," ")
使用错误st[i]=' '
; (strcpy用于复制字符串,是单个字符直接分配的情况下的过程)。gets(st)
现在已从C
中删除,它导致buffer overflows
。使用fgets()
。 Read more on gets() and fgets() 这里可以使用gets()
将fgets()
替换为:-
fgets(st,50,stdin);
修改后的代码:-
#include <stdio.h>
#include <string.h>
int main()
{
char st[50];
int i;
printf("ENter the string:\n");
fgets(st, 50, stdin);
for (i = 0; i < strlen(st); i++)
{
switch (st[i])
{
case '!':
case '"':
case '#':
case '$':
case '%':
case '&':
st[i] = ' ';
break;
}
printf("String is:\n");
puts(st);
}
return 0;
}
推荐:-将puts()
移到for-loop
之外。
输出:-
ENter the string:
!hello#%worl$
String is:
hello#%worl$
String is:
hello#%worl$
String is:
hello#%worl$
String is:
hello#%worl$
String is:
hello#%worl$
String is:
hello#%worl$
String is:
hello %worl$
String is:
hello worl$
String is:
hello worl$
String is:
hello worl$
String is:
hello worl$
String is:
hello worl$
String is:
hello worl
String is:
hello worl
答案 1 :(得分:0)
“”是空格。我认为这不是您的预期行为。使用另一个缓冲区进行复制。例如,
#include<stdio.h>
#include<string.h>
int main()
{
char sta[50];
char stb[50];
int i,j;
printf("ENter the string:\n");
gets(sta);
for(i=0,j=0;i<strlen(sta);i++)
{
switch(st[sta])
{
case '!':
case '"':
case '#':
case '$':
case '%':
case '&': break;
default:
stb[j++]=sta[i];
break;
}
stb[j] = (char)0; // C str termination...
printf("String is:\n");
puts(stb);
}
return 0;
}
答案 2 :(得分:0)
以下建议的代码:
fgets()
而不是(当前)不存在的gets()
函数i
的范围现在,建议的代码:
#include<stdio.h>
#include<string.h>
#define MAX_STR_LEN 50
int main( void )
{
char st[ MAX_STR_LEN + 1 ];
printf("ENter the string, max 50 characters\n");
fgets( st, sizeof( st ), stdin );
for( size_t i=0;i<strlen(st);i++)
{
switch(st[i])
{
case '!':
case '"':
case '#':
case '$':
case '%':
case '&':
st[i] = ' ';
break;
default:
break;
}
}
printf( "Modified String is:\n %s\n", st );
return 0;
}