2

I have these two set of char arrays:

 char t1[]={'1','2','0円','0円'};
 char t2[]={'1','2','3','4'};

I want to write a function to convert them to string, but the string size for t1 should be 2 and for t2 should be 4.

 string convert(char * data)
 {
 return string(data);
 }

Does a good job for t1, but crashes on t2 (t2 is not null terminated).

 string convert(char * data)
 {
 return string(data,data+4);
 }

Does a good job for t2, but the size of generate string for t1 is 4 and not 2.

What is the best way to write a simple and fast function to do this correctly?

asked Oct 15, 2014 at 10:50

2 Answers 2

6

You can take an array by reference. If you're only interested in arrays of size 4:

std::string convert(char const(&data)[4])
{
 return std::string(data, std::find(data, data + 4, '0円'));
}

If you want something more general, you can make it a template:

template<size_t N>
std::string convert(char const(&data)[N])
{
 return std::string(data, std::find(data, data + N, '0円'));
}
answered Oct 15, 2014 at 10:56
1

If you know what is the length of the character array I may suggest you the following:

#include <string>
#include <iostream>
std::string sconvert(const char *pCh, int arraySize){
 std::string str;
 if (pCh[arraySize-1] == '0円') str.append(pCh);
 else for(int i=0; i<arraySize; i++) str.append(1,pCh[i]);
 return str;
}
int main(){
 char t1[]={'1','2','0円','0円'};
 char t2[]={'1','2','3','4'};
 std::string str = sconvert(t1, 4);
 std::cout << str << " : " << str.size() << std::endl;
 str = sconvert(t2, 4);
 std::cout << str << " : " << str.size() << std::endl;
}
answered Oct 15, 2014 at 12:51
2
  • In the else clause you should reserve the string or use assign function. Commented Oct 15, 2014 at 13:02
  • It does but it's inefficient. Commented Oct 15, 2014 at 14:03

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.