总的来说,我对 C 语言和编程还是很陌生。
作为一项家庭作业,我需要制作一个程序,让用户输入一个单词,然后输入一个字母,在该程序中,该程序打印出这些字母在该单词中的位置并打印出没有这些字母的单词(这就是我现在正在苦苦挣扎的地方)。
这是现在的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char word[20];
printf("Enter a word: ");
scanf("%s", word);
int length = strlen(word);
char letter[1];
printf("Enter a letter: ");
scanf("%s", letter);
char newWord[20];
for(int i = 0; i < length; i++){
if(word[i] != letter[0]){
newWord[i] = word[i];
} else
if(word[i] == letter[0]){
printf("%s is at %d\n", letter, i+1);
//newWord[i] = word[i+1]; // I've commented this out because I was testing the first part
// of the loop which is assigning those letters to the variable
// and yet still can't think of an idea that skips that letter
// I want it to skip.
}
}
printf("%s", newWord);
}
基本上我从最后一次打印printf("%s", newWord);
中得到的只是空白。但我想要它做的是例如我输入“worlrdr”和“r”,所以它打印“wold”。甚至一些基本的东西newWord[i] = 'z';
,比如:
for(int i = 0; i < length; i++){
if(word[i] != letter[0]){
newWord[i] = word[i];
}
打印出“zz`zz(一些奇怪的字符)”。我真的很困惑,如果有人能解释一下,我将不胜感激。
提前谢谢你!