C+ how to change array of chars in function - c++

I have this header:
MvProjectQueue & operator >> (char *);
And I have to write a function meeting this spec. (my function should "return" an array of chars using >> operator)
I have to change the passed argument, i.e. I get an array of char when my function is called and I have to modify it (in place).
Normally I would use
MvProjectQueue & operator >> (char **);
got a pointer to char * and I would solved it easily, using something like this:
#include <iostream>
using namespace std;
class SimpleShowcaseObject
{
public:
SimpleShowcaseObject(){};
~SimpleShowcaseObject(){};
SimpleShowcaseObject & operator >> (char ** p_ch)
{
*p_ch = "changed";
cout << "in scope: " << *p_ch << endl;
return *this;
}
};
int main(void)
{
char *ch = new char[10];
ch = "hello";
SimpleShowcaseObject o = SimpleShowcaseObject();
cout << "original: " << ch << endl;
o >> &ch;
cout <<"changed: " << ch << endl;
delete[] ch;
cin.get();
return 0;
}
But this:
#include <iostream>
using namespace std;
class SimpleShowcaseObject
{
public:
SimpleShowcaseObject(){};
~SimpleShowcaseObject(){};
SimpleShowcaseObject & operator >> (char *ch)
{
ch = "changed";
cout << "in scope: " << ch << endl;
return *this;
}
};
int main(void)
{
char *ch = new char[10];
ch = "hello";
SimpleShowcaseObject o = SimpleShowcaseObject();
cout << "original: " << ch << endl;
o >> ch;
cout <<"changed: " << ch << endl;
delete[] ch;
cin.get();
return 0;
}
executes and prints:
original: hello
in scope: changed
changed: hello
and I would like to have
original: hello
in scope: changed
changed: changed
(edited several times, big thanks to everyone for trying to help!)

Your function receive what should be a buffer you can write to:
SimpleShowcaseObject & operator >> (char *ch)
{
//ch = "changed";// with this you are changing the value of the pointer, not what you want
strcpy (ch, "changed");
cout << "in scope: " << ch << endl;
return *this;
}
As other have already pointed out, this is not a good design: your operator >> has to write a string (char[]) in a buffer, without knowing the lenght of input buffer; not a nice scenario.

Related

How to declare function using reference?

I am making this program to check the alphabetic and numeric characters of a C-type string. I am using C-type strings because it is for an assignment, otherwise I would opt to use std::string.
How do I declare the function? In my case, I want str, SAlpha and SNum, to be stored in the function as s, alpha, num. That's why I am using references, but I don't understand how to declare it without giving me an error saying undefined.
I have been searching, but I am new to functions, and don't understand them quite well. That's why I'm asking.
Below is the code:
#include <iostream>
#include <cstring>
#include <cctype>
using namespace std;
void seperate(char (&s)[], char (&alpha)[], char (&num)[]);
int main() {
char str[100];
char SAlpha[100];
char SNum[100];
cout << "Insert a string: ";
cin.getline(str,100);
strcpy(SAlpha, str);
strcpy(SNum,str);
cout << "Alphabetic characters " << endl;
for (int i = 0; i < strlen(SAlpha); i++) {
if (isalpha(SAlpha[i])) {
cout << " " << SAlpha[i];
}
}
cout << endl;
cout << "Numeric characters " << endl;
for (int i = 0; i < strlen(SNum);i++) {
if (isdigit(SNum[i])) {
cout << " " << SNum[i];
}
}
seperate(str, SAlpha, SNum); //UNDEFINED FUNCTION
return 0;
}
You are getting an "undefined" error because you have only declared the seperate() function but have not implemented it yet, eg:
#include <iostream>
#include <cstring>
#include <cctype>
using namespace std;
// THIS IS JUST A DECLARATION!!!
void seperate(char (&s)[100], char (&alpha)[100], char (&num)[100]);
int main() {
char str[100];
char SAlpha[100];
char SNum[100];
cout << "Insert a string: ";
cin.getline(str,100);
strcpy(SAlpha, str);
strcpy(SNum,str);
cout << "Alphabetic characters " << endl;
for (int i = 0; i < strlen(SAlpha); i++) {
if (isalpha(SAlpha[i])) {
cout << " " << SAlpha[i];
}
}
cout << endl;
cout << "Numeric characters " << endl;
for (int i = 0; i < strlen(SNum);i++) {
if (isdigit(SNum[i])) {
cout << " " << SNum[i];
}
}
seperate(str, SAlpha, SNum); // <-- OK TO CALL SINCE THE FUNCTION IS DECLARED ABOVE...
return 0;
}
// ADD THIS DEFINITION!!!
void seperate(char (&s)[100], char (&alpha)[100], char (&num)[100])
{
// do something here...
}

Binary char array into stringstream and pop from the buffer

I have 20byte binary char array. I want to divide into 3 parts: 4byte, 8byte, 8byte. I implemented it like the following. It works but seems I might be able to use buffer stream. I want to know how to use it.
Now
void main()
{
// _data is 20byte binary char array. 0000000000000000000000000000000000000000000001111001110001111111001110000010110000001011101101000000000000000000000000000000000000000000000000000000000000000001
// strA (4 byte)
string strA;
for (std::size_t i = 0; i < 4; ++i) {
strA += bitset<8>(_data.c_str()[i]).to_string();
}
cout << strA << endl; // 00000000000000000000000000000000
// strB (8 byte)
string strB;
for (std::size_t i = 4; i < 12; ++i) {
strB += bitset<8>(_data.c_str()[i]).to_string();
}
cout << strB << endl; // 0000000000000111100111000111111100111000001011000000101110110100
// strC (8 byte)
string strC;
for (std::size_t i = 12; i < 20; ++i) {
strC += bitset<8>(_data.c_str()[i]).to_string();
}
cout << strC << endl; // 0000000000000000000000000000000000000000000000000000000000000001
}
Expectation
I want to implement like this.
void main()
{
stringstream ss = _data;
strA = ss.pop(4);
strB = ss.pop(8);
strC = ss.pop(8);
}
Update 1
Thank you guys. I'm trying all of answers you gave me one by one. I'm newbie in c++ so it takes time to understand it. The following is Anders K's one.
struct S { char four[4]; char eight1[8]; char eight2[8]; };
struct S *p = reinterpret_cast<S*>(&_data);
cout << p->four << endl; // => Output "(" I think I can find way to output
Update 2
It works using string::substr. Thanks Zakir.
int main()
{
// I don't know how to change to string value in smart way..
string str;
for (std::size_t i = 0; i < _data.size(); ++i) {
str += bitset<8>(_data.c_str()[i]).to_string();
}
cout << str << endl; // 0000000000000000000000000000000000000000000001111001110001111111001110000010110000001011101101000000000000000000000000000000000000000000000000000000000000000001
std::string d = str; // Your binary stream goes here
int lenA = (4*8); // First 4 Bytes
int lenB = (8*8); // Second 8 Bytes
int lenC = (8*8); // Last 8 Bytes
std::string strA = d.substr(0, lenA);
std::string strB = d.substr(lenA + 1, lenB - 1);
std::string strC = d.substr(lenA + lenB + 1, lenC - 1);
cout << strA << endl; // 00000000000000000000000000000000
cout << strB << endl; // 000000000000111100111000111111100111000001011000000101110110100
cout << strC << endl; // 000000000000000000000000000000000000000000000000000000000000001
}
Update 3
I got an error when I try Scheff's way. This is my fault and I think I can solve it. And I think I should reconsider about _data's type.
int main
{
const char data = _data;
const char *iter = data;
string strA = pop(iter, 4);
string strB = pop(iter, 8);
string strC = pop(iter, 8);
cout << "strA: '" << strA << "'" << endl;
cout << "strB: '" << strB << "'" << endl;
cout << "strC: '" << strC << "'" << endl;
}
Make Error Message
error: no viable conversion from 'string' (aka 'basic_string<char, char_traits<char>, allocator<char> >') to
'const char'
const char data = _data;
It is not possible to make a new method for std::stringstream. (At least, I would not recommend this.)
Instead, I would suggest to make it a function. The usage would be similar.
#include <bitset>
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
string pop(istream &in, size_t n)
{
string ret;
while (n--) {
unsigned char byte = (unsigned char)in.get();
ret += bitset<8>(byte).to_string();
}
return ret;
}
int main()
{
string data(
"\x11\x22\x33\x44\x55\x66\x77\x88\x99\xaa"
"\xbb\xcc\xdd\xee\xff\xde\xad\xbe\xef\x00", 20);
istringstream in; in.str(data);
string strA = pop(in, 4);
string strB = pop(in, 8);
string strC = pop(in, 8);
cout << "strA: '" << strA << "'" << endl;
cout << "strB: '" << strB << "'" << endl;
cout << "strC: '" << strC << "'" << endl;
return 0;
}
Output:
strA: '00010001001000100011001101000100'
strB: '0101010101100110011101111000100010011001101010101011101111001100'
strC: '1101110111101110111111111101111010101101101111101110111100000000'
Note:
Using a std::istream makes it applicable to any stream derived from std::istream.
There is no error handling in pop(). Thus, the returned result of pop() might be wrong if the passed stream isn't good() afterwards.
Btw. I agree with the comments that a std::stream might be "over-engineered". Thus, here the "light-weight" version:
#include <bitset>
#include <iostream>
#include <string>
using namespace std;
string pop(const char *&iter, size_t n)
{
string ret;
while (n--) {
ret += bitset<8>((unsigned char)*iter++).to_string();
}
return ret;
}
int main()
{
const char data[] =
"\x11\x22\x33\x44\x55\x66\x77\x88\x99\xaa"
"\xbb\xcc\xdd\xee\xff\xde\xad\xbe\xef\x00";
const char *iter = data;
string strA = pop(iter, 4);
string strB = pop(iter, 8);
string strC = pop(iter, 8);
cout << "strA: '" << strA << "'" << endl;
cout << "strB: '" << strB << "'" << endl;
cout << "strC: '" << strC << "'" << endl;
return 0;
}
The output is identical like above.
Note:
The usage of char[] and char* is much more sensitive for out-of-bound access. Thus, it has to be used carefully.
I'm not quite sure whether the (unsigned char) cast is necessary. As I have often seen "funny" effects concerning char, int and sign extension, I guess it cannot hurt. (I feel better with it.)
I can propose you a very simple alternative using string::substr
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string _data="00010001001000100011001101000100\
0101010101100110011101111000100010011001101010101011101111001100\
1101110111101110111111111101111010101101101111101110111100000000";
int lenA = (4*8); //First 4 Bytes
int lenB = (8*8); //Second 8 Bytes
int lenC = (16*8); //Last 16 Bytes
string strA = _data.substr(0, lenA - 1);
string strB = _data.substr(lenA, lenB - 1);
string strC = _data.substr(lenB, lenC - 1);
std::cout << "strA: " << strA << endl;
std::cout << "strB: " << strB << endl;
std::cout << "strC: " << strC << endl;
return 0;
}
This is neat and simple but gets your job done!
Demo here
Output:-
strA: 0001000100100010001100110100010
strB: 010101010110011001110111100010001001100110101010101110111100110
strC: 100110011010101010111011110011001101110111101110111111111101111010101101101111101110111100000000

non-helper << operator not working C++

I'm trying to overload the << operator for the display function call.
Heres my code:
#include <iostream>
#include <cstring>
using namespace std;
// global variable
const int MAX = 3;
// class definition
class CString{
char str[MAX+1];
public:
CString(char* param){
if(param == nullptr){
str[0] = '\0';
return;
}
strncpy(str,param,MAX);
str[MAX] = '\0';
}
void display(ostream& os){
os << str;
}
};
// << operator overloading
ostream& operator << (ostream& os, CString& cs){
static int call = 0;
os << call << ": ";
cs.display(os);
call++;
return os;
}
void process(char* parm){
CString cs(parm);
// here is where my issue is
cs.display(cout);
cout << endl;
}
//----------------------------------------------------------------
int main(int argc,char *argv[]){
cout << "Command Liine : ";
for(int arg = 0; arg < argc ; arg++){
cout << " " << argv[arg];
}
cout << endl;
if( argc == 1){
cout << "Insufffiecentnumber of arguemnts (min1)" << endl;
return 1;
}
cout << " Maxium numver of characters stored: " << MAX << endl;
for(int arg = 1; arg < argc; arg++){
process(argv[arg]);
}
return 0;
}
EDIT:
Here is the correct output and the output I have:
Correct:
Command Line : w1 oop345 btp305
Maximum number of characters stored : 3
0: oop
1: btp
Mine:
Command Line : w1 OOP345 DBS305
Maxium number of characters stored: 3
OOP
DBS
I'm having an issue with my << operator not working, I can't seem to figure it out. The ostream& operator<<(ostream& os, CString& cs) does not seem to be loading its syntax.
Question:
Does anyone know where my mistake has been made?
You wrote a correct overloading of << operator, but in method process() you used a public method display() of class CString instead of using << operator directly.
Just change one line in method process():
cs.display(cout); to: cout << cs;
void process(char* parm){
CString cs(parm);
// here is where my issue is
cout << cs;
cout << endl;
}
P.S. you do not need method CString::display at all as you already overload << operator for this class.

Writing value to c style string in struct

For the life of me I can't figure out why the I can't write to a c style string inside of a struct.
College student - can't use string class, haven't learned pointers.
Help? 2 hours at trying to figure this out.
#include <iostream>
using namespace std;
void strCopy(char from[], char to[])
{
for (int i = 0; i < 255; i++)
{
to[i] = from[i];
}
}
struct card
{
char suit[20];
char rank[20];
int cvalue;
char location[20];
};
void printCard(card card)
{
cout << card.rank << " of " << card.suit << endl;
}
int main()
{
// I don't think strCopy()'s the problem, I've used it with my last project.
cout << "Test strCopy()" << endl;
char str1[14] = "abcdefghijklm";
char str2[14];
strCopy(str1, str2);
cout << " " << str2 << endl << endl;
// Now the negative.
card one;
one.cvalue = 2;
strCopy("Somewhere", one.location);
strCopy("Two", one.rank);
strCopy("Hearts", one.suit);
printCard(one);
}
// I don't think strCopy()'s the problem, I've used it with my last
project.
Wrong
for (int i = 0; i < 255; i++)
{
to[i] = from[i];
}
copies 255 characters, however that's not what you meant.
If here :
strCopy(str1, str2);
cout << " " << str2 << endl << endl;
Your're getting "correct" output, then you're just unlucky, since that invokes an undefined behavior, an you're writing off the end of the array.

crash, delete [ ] this->str

Hello I've got some troubles to delete a member string of my class which is isn't null and which points to the right location since I can display my string "hello world" just before.
I call the function mystringclass::alloc() from another member function afterwards this->str was supposed to get another string content larger.
The process worked fine a first time when I resized the same way "hello" to get "hello world". But now I want to enlarge it again it doesn't. So I'm confused.
Please help me.
void mystringclass::alloc(long newsize) //newsize includes the +1 char
{
cout << "old size was: " << this->size << endl; //displays "12"
if(this->str) cout << this->str << endl; //displays "hello world" all is right till here
if(this->str) delete [] this->str ; //it crashes here
cout << "str deleted\n"; //never show up on screen
this->str = new char[newsize + 1];
this->size = newsize;
this->str[0] = 0;
}
Thanks for your answers, I tried to clear my code to post it here. My bug disappeared but another one came up and having something to do with the rule of three:
int main()
{
stringclass str = "Hello";
stringclass str2 = str;
return 0;
}
I display info all along procedures So the problem is that str2 is already equal to "hello" even before affecting the content of str in my copy constructor. And is empty after the copy. What's wrong? As some may say, I learned c++ in a magicbox. I'm using codeblocks 10.05
Full code :
#include <fstream>
#include <iostream>
#include <vector>
using namespace std;
class stringclass
{
protected :
inline bool success() { failbit = false; return true; }
inline bool fail() { failbit = true; return false; }
public :
bool failbit;
char * mystring;
long memsize;
long length;
void alloc(long newsize);
void reset();
void copy(const stringclass & other);
stringclass() {reset(); }
stringclass(const stringclass & other) {copy(other); }
stringclass(const char str[]);
~stringclass() {delete [] mystring;}
inline long get_length() { if(mystring) length = strlen(mystring); return length;}
inline long get_memsize() const { return memsize; }
friend ostream& operator << (ostream& out, stringclass & sc){out << sc.mystring; return out;}
stringclass & operator = (stringclass & other) { copy(other); return *this;}
};
void stringclass::reset()
{
delete [] mystring;
mystring = NULL;
length = 0;
memsize = 0;
}
void stringclass::alloc(long newsize)
{
cout<< "\nalloc(long newsize)... \n" << endl;
cout << "memsize was : " << memsize << endl;
cout << "length was : " << length << endl;
if(mystring) cout << "mystring = " << mystring << endl;
delete [] mystring;
cout << "mystring deleted...\n";
mystring = new char[newsize];
cout << "mystring has been resized\n";
mystring[0] = 0;
memsize = newsize;
length = strlen(mystring);
cout << "memsize is now : " << memsize << endl;
cout << "length is now : " << length << endl;
cout<< "\nend of alloc()... " << endl;
cout << "\n";
}
void stringclass::copy(const stringclass & other)
{
cout << "\n";
cout << "copy(const stringclass & other)...\n" << endl;
cout << "other.mystring = "<< other.mystring << endl;
if(other.mystring == NULL || other.memsize == 0)
{
reset();
return;
}
alloc(other.memsize);
strcpy(mystring, other.mystring);
cout << "mystring = "<< mystring;
length = strlen(mystring);
cout << "length: " << length << endl;
cout<< "\nend of copy()... " << endl;
cout << "\n";
}
stringclass::stringclass(const char str[]) : mystring(NULL), memsize(0), length(0)
{
if(str == NULL) reset();
else
{
alloc(strlen(str) + 1);
strcpy(mystring, str);
length = strlen(mystring);
}
}
int main()
{
stringclass str = "Hello";
stringclass str2 = str;
cout << "\nback to main()...\n";
cout << "str = " << str << "\n";
cout << "str2 = " << str2 << "\n";
cout << endl;
system("PAUSE");
return 0;
}
Result on screen :
alloc(long newsize)...
memsize was : 0
length was : 0
mystring deleted...
mystring has been resized
memsize is now : 6
length is now : 0
end of alloc()...
copy(const stringclass & other)...
other.mystring = Hello
alloc(long newsize)...
memsize was : 3214960
length was : 2293560
mystring = Hello
mystring deleted...
mystring has been resized
memsize is now : 6
length is now : 0
end of alloc()...
mystring = length: 0
end of copy()...
back to main()...
str =
str2 =
Appuyez sur une touche pour continuer...
I've just realized that the following code isn't necessary for you :
protected :
inline bool success() { failbit = false; return true; }
inline bool fail() { failbit = true; return false; }
public :
bool failbit;
So I put off these two functions and this variable, and guess what.. all worked fine, no bug. They are not even used once. I put it back and the problem came back as well. How could you explain that?! I'm already losing my hairs.
The fact that you can "display" a string says absolutely nothing unfortunately. De-allocating the string will still make it printable, most likely until it's overwritten by a new llocation and initialization.
Just try to print the string after you've delete[]d it and see.