Code: |
/* 1.1 – C string usage */ char mystring[] = “Hello!”; /* 1.2 – C++ std::string usage */ #include <string> std::string mystring = “Hello!”; |
Code: |
/* 1.3 – array of std::string */ std::string mystring[] = “Hello!”; // Note this won't compile! |
Code: |
/* 1.4 – Importing namespace std into the global namespace */ #include <string> using namespace std; string mystring = “Hello!”; |
Code: |
/* 1.5 – Importing std::string into the global namespace */ #include <string> using std::string; string mystring = “Hello!”; |
Code: |
/* 1.6 – Use of c_str() */ string command = “cd /home/andrew/”; system(command.c_str()); |
Code: |
/* 2.1 – gets() and fgets() */ #define BUFFERSIZE 1024 char* buffer = malloc(BUFFERSIZE); /* a 1024-character buffer */ char* s; s = gets(buffer); /* reads into buffer until newline. UNSAFE! */ s = fgets(buffer, BUFFERSIZE, stdin); /* reads into buffer until newline -or- until 1023 characters have been read. SAFER! */ |
Code: |
/* 2.2 – std::getline() */ string buffer; getline(cin, buffer); /* reads from cin (the C++ stream equivalent to C's stdin) into string buffer, expanding buffer as needed */ |
Code: |
/* 2.3 - strcpy, strncpy and C++ string copy */ char p[] = "Hello\n"; char* q = malloc(4); strcpy(q, p); /* Dangerous! */ strncpy(q, p, 4); /* safe! */ string s = "Hello\n"; string t; t = s; /* safe! */ |
Code: |
/* 3.1 - std::string based recv() */ #include <string> #include <socket.h> #include <sys/types.h> using std::string; ssize_t recv(int s, string& buf, size_t len, int flags) { char* buffer = new char[len]; ssize_t bytes_recv = recv(s, (void*) buffer, len, flags); buf = string(buffer); delete[] buffer; return bytes_recv; } |
Code: |
/* 3.2 - std::string based send() */ #include <string> #include <socket.h> #include <sys/types.h> using std::string; ssize_t send(int s, std::string& buf, int flags) { return send(s, buf.c_str(), buf.length(), flags); } |
output generated using printer-friendly topic mod, All times are GMT + 2 Hours