如何调试用于按空间分割数组的代码
How to debug this code written to split an array by space?
我需要编写一个程序来获取一个句子并通过分隔符(空格)分割它的单词;所以我编写了下面的代码,但它似乎不能正常工作。知道怎么调试这段代码吗?例如:
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可以用更少的代码行来完成这个任务
相关文章:
- 将自定义可绘制对象存储在数组中会导致绘制时出现分割错误
- 数组不会存储超出第一个空间的范围
- C 2D数组导致分割故障(核心倾倒)
- 将数组类型更改为 Int16 会节省存储空间吗?
- 这两个代码之间的差异(为什么我的数组也有额外的空间,即使我限制了它)
- 试图创建动态分配的char数组时的分割故障
- 为多维数组创建内存空间
- 分割故障 - 遇到问题,创建新的数组实例
- C++的新增功能:创建 2D 数组并具有正确的赋值运算符:分割错误
- 从方法返回的数组上的 C++ 分割错误
- C ++编译指示OMP分割错误(数据竞争?)与数组
- 从数组中添加值并插入空间
- 处理2D数组时的分割故障
- 具有相同数组索引的C 分割故障
- 字符串的变体数组包含替代空间
- 试图打印出/加载2D数组时的分割故障
- C++在具有O(n)空间的数组中查找第一个非重复整数
- 使用O(n)时间和O(1)空间从数组中查找丢失的数字
- 分割数组字符
- 如何调试用于按空间分割数组的代码