[英]program to remove special characters and number from string and only print english letter
這就是我嘗試過的。 這對於像wel $ co * me這樣的小字符串正常工作,但是卻為pass @ word提供了奇怪的輸出。 我到底在哪里錯?
#include <stdio.h>
#include <string.h>
int main()
{
char s[100],rs[100];
int i,c=0;
scanf("%s",s);
int n = strlen(s);
for(i=0;i<n;i++)
{
if(((int)s[i] >= 65 && (int)s[i] <= 90) ||((int)s[i] >=97 && (int)s[i] <= 122) )
{
rs[c] = s[i];
c++;
}
else
{
continue;
}
}
printf("%s",rs);
return 0;
}
但是給出了pass @ word的奇怪輸出。 我到底在哪里錯?
printf("%s",rs);
期望rs
是一個指向字符串的指針。 但是,在rs
指向的數據中沒有特定的空字符時,結果是未定義的行為,或者在OP的情況下為“奇怪的輸出”。
一個簡單的解決方案是
rs[c] = '\0'; // add this after the loop
printf("%s",rs);
另一個重要的方面是避免緩沖區溢出-使用寬度限制。
// scanf("%s",s);
scanf("%99s",s);
代碼還有其他弱點,但這是目前的關鍵。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.