c++ - How to debug this code written to split an array by space? -
i need write program sentence , split words delimiter(space);so i've wrote code below doesn't seem working properly. idea's how debug code? example:
input: meet me tonight desired output: meet me tonight given output: meet me ton ght
i'm confused why output not expect. here's i've come far:
#include <iostream> using namespace std; const int buffer_size=255; int main() { char* buffer; buffer = new char[255]; cout << "enter statement:" << endl; cin.getline(buffer, buffer_size); int q=0, numofwords=1; while(buffer[q] != '\0') { if(buffer[q] == ' ') numofwords++; q++; } char** wordsarray; wordsarray = new char* [numofwords]; int lenofeachword = 0, num = 0; int* sizeofwords = new int [numofwords]; for(int i=0; i<q; i++) { if(buffer[i]==' ') { sizeofwords[num] = lenofeachword; wordsarray[num] = new char[lenofeachword]; num++; }else lenofeachword++; } sizeofwords[num] = lenofeachword; wordsarray[num] = new char[lenofeachword]; int k=0; for(int i=0; i<numofwords; i++) { for(int j=0; j<sizeofwords[i]; j++) { wordsarray[i][j] = buffer[k]; k++; } k++; } for(int i=0; i<numofwords; i++) { for(int j=0; j<sizeofwords[i]; j++) { cout << wordsarray[i][j]; } cout << endl; } }
the problem snippet (comment):
if(buffer[i]==' ') { sizeofwords[num] = lenofeachword; wordsarray[num] = new char[lenofeachword]; num++; }else{ lenofeachword++; // <- keeps increasing }
so snippet skip lot of strings , possibly cause seg fault somewhere along line:
for(int i=0; i<numofwords;i++){ for(int j=0;j<sizeofwords[i];j++) { wordsarray[i][j]=buffer[k]; k++; } k++; }
also if c++, why still using c-style write program? simple stringstream strings in less lines of code
Comments
Post a Comment