0
#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?

YSC
  • 38,212
  • 9
  • 96
  • 149
  • 6
    `zaman_string[i]` is a `char`. It has no `c_str()` method. `strcat` shouldn't be here *at all* and you should be using `tutucu.append(1, zaman_string[i]);`. Whatever C text you're trying to learn C++ from, stop it. – WhozCraig Dec 07 '20 at 09:30
  • 5
    `tutucu += zaman_string[i];` is presumably what you're trying to do. – Retired Ninja Dec 07 '20 at 09:33

3 Answers3

4

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 ':'.

YSC
  • 38,212
  • 9
  • 96
  • 149
1

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";
    }
}
tango-2
  • 94
  • 1
  • 10
  • This is similar to YSC's answer, but it shows that you don't even need a `result` variable. You can combine this with the range-for from YSC's answer. – MSalters Dec 07 '20 at 11:04
1

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.

MSalters
  • 173,980
  • 10
  • 155
  • 350