c++ - 如何调试为按空格拆分数组而编写的代码?

标签 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; 
   }
}

最佳答案

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

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

所以这段代码会跳过很多字符串,并可能在某处导致段错误:

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来写这个程序?一个简单的stringstreamstrings将以更少的代码行完成此操作

关于c++ - 如何调试为按空格拆分数组而编写的代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22292681/

相关文章:

c++ - 从剪贴板获取多个 Outlook 附件

c++ - 我应该如何将成员函数指针传递给 OpenCV 中的 setMouseCallback?

C++使用宏定义单个类的类成员

c++ - 编译多源文件时 Unresolved external 问题

c++ - 测试回文时程序不会继续运行 (C++)

c++ - 调试错误 R6010

c++ - 如何在 C++ 中逐行搜索并返回匹配的行

c++ - 静态获取成员变量的偏移量

c++ - 函数 __gnu_cxx::__STL_next_prime(usigned long) 有什么作用?

c++ - cmake 检测 clang-cl 为 clang