index of value in table .c++

I have to create a function which receives in parameter an array of characters and a character. it must return the positions of this character in the array. I have prepared this code but it does not work on codeblocks. yet it works with dev ++. who can help me?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
  void repererposition(char t[], char c)
{
int i=0;
cout<<"\n La lettre  "<<c<<"  apparait aux positions : ";
while(t[i]!='\0')
{

if(t[i]==c)
cout<<i<<"\t";i++;

}
cout<<endl;
}
What is the error you get while working within codeblocks? It sounds like you're having more of an IDE issue and not a code issue. Show the full code (with main).
Last edited on
it must return the positions of this character in the array.


Then the above code, even if working with dev++, is not what is required as it doesn't return anything. However, to just display the character positions then:

1
2
3
4
5
6
7
8
9
10
void repererposition(const char t[], char c)
{
	std::cout << "\n La lettre  " << c << "  apparait aux positions : ";

	for (auto p {t}; p && *p; ++p)
		if (*p == c)
			std::cout << p - t << '\t';

	std::cout << '\n';
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <cstring>

// return the position of the character in the c-style string
// return -1 if the character is not found
inline std::ptrdiff_t repererposition( const char cstr[], char ch )
{
    if( cstr != nullptr && ch != 0 )
    {
        // https://en.cppreference.com/w/cpp/string/byte/strchr
        const auto ptr = std::strchr( cstr, ch ) ;
        if( ptr != nullptr ) return ptr - cstr ;
    }

    return -1 ; // the character is not found
}
Topic archived. No new replies allowed.