如何调试用于按空间分割数组的代码

How to debug this code written to split an array by space?

本文关键字:空间分割 数组 代码 用于 何调试 调试      更新时间:2023-10-16

我需要编写一个程序来获取一个句子并通过分隔符(空格)分割它的单词;所以我编写了下面的代码,但它似乎不能正常工作。知道怎么调试这段代码吗?例如:

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] != '')
   {
      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; 
   }
}

问题是这个代码片段(注释):

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风格写这个程序?一个带有字符串的简单stringstream可以用更少的代码行来完成这个任务