很难指出C中char数组(用户输入)中一个字符(用户输入)的所有位置 [英] Difficulty pointing out all of the positions of one character (user input) in char array (user input) in C

查看:64
本文介绍了很难指出C中char数组(用户输入)中一个字符(用户输入)的所有位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一年级学生,所以我仍在努力学习C语言.

I'm a first year student so I'm still struggling with C language.

其中一项任务是让我编写一个程序,在该程序中,用户输入一个单词,然后输入一个字母,该程序将使用该字母查找该单词中所有字母的位置(假设他进入"world"和"r",脚本会打印出"r位置在3"/或"worldr""r位置在3和6"/或"worldrr""r位置在3 6和7").

One of the assignments want's me to make a program where user inputs a word then a letter which the program will use to find all of the letters positions in that word (lets say he enters 'world' and 'r' so the script prints out 'r positions are in 3' / or for 'worldr' 'r positions are in 3 and 6' / or for 'worldrr' 'r positions are in 3 6 and 7').

#include <stdio.h>
#include <stdlib.h>
#include <string.h>


int main()
{

char word[20];

    printf("Enter a word: ");
    scanf("%s", word);

    char letter;
    printf("Enter a letter: ");
    scanf(" %c", letter);

    for(int i = 0; i < strlen(word); i++){

        if(word[i] == letter){

            printf(" %c positions are in %d", letter, i+1);

        }

    }



}

该程序还会跳过" scanf(%c",letter); "如果我写%c而不在开头的" scanf("%c,letter); "像这样为什么?

ALSO the program skips "scanf(" %c", letter);" part (error but nothing in logs) if I write %c without the space in the beginning "scanf("%c", letter);" like so. Why?

基本上,如果我写 if(word [i] =='r'){而不是 if(word [i] == letter){很好,但是不会像我需要的那样工作.我一直在寻找解决方案,但是除了尝试 strchr 外别无他法,但是我需要它来打印出阵列位置,而不是实际的内存ram位置或类似的东西,或者也许我只是不太了解因为我以前从未使用过它,所以得到它.如果是这样,那么如果有人可以向我解释如何使用 if(word [i] == letter){ strchr 的方式来解决我的问题,我将不胜感激.我很想了解两者.

Basically If I write if(word[i] == 'r'){ instead of if(word[i] == letter){ it works just fine but It won't work like I need it to. I've searched for a solution but no luck other than to try strchr but I need it to print out the array position not the actual memory ram position or something like that or maybe I just don't quite get it yet since I haven't used it before ever. If so I would greatly appreciate If someone could explain me how to solve my problem using if(word[i] == letter){ and strchr ways. I'd love to understand both.

谢谢你!

推荐答案

遇到此问题的任何人都可以:

Alright to anyone who comes across this issue:

显然,if循环中的 strlen(word)不起作用,这就是问题所在.要修复它,我必须创建 int lenght = strlen(word); char letter; 之上,由于某些我不了解的原因,这一点很重要.也将带有scanf的letter变量更改为 char letter [1]; ,将其scanf更改为 scanf(%s",letter); .

Apparently strlen(word) in the if loop didn't work that was the problem. To fix it I had to create int lenght = strlen(word); ABOVE char letter; and it's important for some reason I don't yet understand. Also changed the letter variable to char letter[1]; with scanf to scanf("%s", letter);.

这篇关于很难指出C中char数组(用户输入)中一个字符(用户输入)的所有位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆