'c_str() method not recognised on my string

#include <iostream>
#include <cstring>
#include <string>    

void parcala(string zaman_string)
    {
        string tutucu;
        
        for(int i=0;i<zaman_string.length();i++)
        {
            
            if(zaman_string[i]!=':')
            {
                strcat(tutucu,zaman_string[i].c_str());
            }
            else
            {
                cout<<tutucu<<endl;
                tutucu="";
            }
        }
    }

I'm getting this error when compiling the above function:

Error= [Error] request for member 'c_str' in zaman_string. std::basic_string<_CharT,
_Traits, _Alloc>::operator[]<char, std::char_traits<char>, std::allocator<char>>
(((std::basic_string<char>::size_type)i))', which is of non-class type 'char'

Why strcat is rejected? IS there any alternative for strcat?



Solution 1:[1]

You are mixing the different ways in C++ to handle strings.

  • strcat and other str... function work on char*, that is arrays of char.
  • .c_str(), .length() are member functions of the std::string class.

You should choose one set of tools and stick with it. I'd strongly recommand to use std::string. With a few improvements to better reflect the idiomatic C++ of this millennia1:

#include <string>
#include <iostream>

void parcala(std::string const& zaman_string) // [1]
{
    std::string result; // [2]
    
    for (auto c : zaman_string) { // [3]
        if (c == ':') {
            std::cout << result << '\n'; // [4]
            result.clear();
        } else {
            result += c;
        }
    }
}

1) An additional improvement would be to define a generic split function (taking a string and returning an array of string_views) and use that split function on separator ':'.

Solution 2:[2]

Looks like you might be better of with a slightly different approach:

replace(begin(zaman_string), end(zaman_string), ':', '\n');
std::cout << saman_string << std::endl;

std::replace comes from <algorithm>. This header has a lot of functions which can replace manual loops.

Solution 3:[3]

You can use this code

void fun(const std::string& param) {

   for (int i = 0 ; i < param.length() ; ++i) {
      if(param[i] != ':')
        std::cout << param[i];
      else
        std::cout << "\n";
    }
}

Solution 4:[4]

Because you've used the single quote ' instead of the back tick `. Since you didn't use the back tick, the code didn't use your variable

So you should change that line to:

audioElement.src = `songs/${index+1}.mp3`; 

You can read more about it here.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 MSalters
Solution 3
Solution 4 Kevin