【发布时间】:2020-12-08 19:07:46
【问题描述】:
总的来说,我还是 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(一些奇怪的字符)”。我真的很困惑,如果有人能解释一下,我将不胜感激。
谢谢你!
【问题讨论】:
-
如果将有效字符复制到与原始字符相同的位置,则会出现未初始化数据的间隙。您将需要两个索引:如果从“beer”中去掉“e”,则位置 3 的“r”将位于新字符串中的位置 1。确保以空字符
'\0'终止新字符串,使其成为正确的 C 字符串。 -
(顺便说一下,你不能扫描到长度为1的数组,因为
scanf想在最后放置一个空字符。你也不知道用户是否只输入了一个信。) -
@MOehm 哦,对了。这就解释了为什么如果我只使用
newWord[i] = 'z';会得到奇怪的字符 -
正如我在your other question 中已经指出的,最好写
char letter;而不是char letter[1];,写scanf(" %c", &letter);而不是scanf("%s", letter);。 -
@AndreasWenzel 是的!谢谢!
标签: arrays c char assign behavior