如何调试这个用空格分割数组的代码?

时间:2014-03-10 05:29:18

标签: c++

我需要编写一个程序来获取一个句子并用分隔符(空格)分割它的单词;所以我已经编写了下面的代码,但它似乎没有正常工作。任何想法如何调试此代码? 例如:

input:
    meet me tonight
desired output: 
    meet 
    me
    tonight
given output:  
    meet
    me ton 
    ght

我真的很困惑为什么输出不是我所期望的。这是我到目前为止所提出的:

#include <iostream>
using namespace std;
const int BUFFER_SIZE=255;

int main()
{       
   char* buffer;
   buffer = new char[255];
   cout << "enter a 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; 
   }
}

1 个答案:

答案 0 :(得分:2)

问题是这个片段(评论):

if(buffer[i]==' ')
{
    sizeofwords[num] = lenofeachword;
    wordsArray[num] = new char[lenofeachword];
    num++;
}else{
    lenofeachword++; // <- this keeps increasing
}

所以这个片段会跳过很多字符串,并可能导致某个地方出现seg故障:

for(int i=0; i<numofwords;i++){
    for(int j=0;j<sizeofwords[i];j++)
    {
        wordsArray[i][j]=buffer[k];
        k++;
    }
    k++;
}

另外如果这是c ++,那你为什么还在用c-style编写这个程序?使用stringstream的简单strings可以在较少的代码行中执行此操作