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

I need to write a program that get a sentence and split its words by a delimiter(space);so I've wrote the code below but it doesn't seem to be working properly. any idea's how to debug this code?
for example:
input:
meet me tonight
desired output:
meet
me
tonight
given output:
meet
me ton
ght
I'm really confused why the output is not what I expect. Here's what I've come up with so far:
#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;
}
}

The problem is this snippet (comment):
if(buffer[i]==' ')
{
sizeofwords[num] = lenofeachword;
wordsArray[num] = new char[lenofeachword];
num++;
}else{
lenofeachword++; // <- this keeps increasing
}
So this snippet will skip a lot of the strings and possibly cause a seg fault somewhere along the 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 this is c++, then why are you still using c-style to write this program? A simple stringstream with strings will do this in less lines of code

Related

filling 2d char array and accessing each element

It's my first question in stack overflow so if there is some mistakes sorry about that. I'm trying to fill a 2d char array and then access each letter. I complied my code, there is no error but when I try to run it doesn't work. Here it's my code.
#include<iostream>
#include<string>
#include<stdlib.h>
using namespace std;
int main() {
char ch[] = "Welcome text in a separate line.";
char strWords[5][7];
int counter = 0;
int a = 0;
for (int i = 0; i < sizeof(ch); i++) {
if (ch[i] == ' ') {
strWords[counter][a] = '\0';
counter++;
a = 0;
}
else
{
strWords[counter][a] += ch[i];
a++;
}
}
for (int i = 0; i <= 5; i++) {
for (int a = 0; a <= 7; a++) {
cout << strWords[i][a] << " ";
}
}
return 0;
}
A few things wrong with your code
int main() {
char ch[] = "Welcome text in a separate line.";
// char strWords[5][7]; <<<=== i would change to be larger that you need, just in case
char strWords[20][20];
int counter = 0;
int a = 0;
for (int i = 0; i < strlen(ch); i++) { // sizeof is wrong, you need strlen
if (ch[i] == ' ') {
strWords[counter][a] = '\0';
counter++;
a = 0;
}
else
{
//strWords[counter][a] += ch[i];
strWords[counter][a] = ch[i]; // you do not need to try to concatenate, you are already walking down the buffer with 'a'
a++;
}
}
for (int i = 0; i < counter; i++) { // use 'counter' as it has the number of lines
// since you 0 terminated the string you do not need to walk character by character
cout << strWords[i] << " ";
}
return 0;
}
You are also not detecting and terminating the last word (since there is no space after it). I will leave that to you. The code I show does not print the word 'line.'
You should really have tests to make sure you do not overflow the length or number of words.
Plus you should ideally use std::string and std::vector
Note - if, for experimentation, you do want to walk through char by char to output the strings you should look for the terminating '0' character and exit the inner loop

How can I make diagonal shapes in C++?

I currently have some problem with looping. Please help me to make some program that run like this :
But I have made some program that runs kind of like this :
And this is my code for my program. Maybe you can correct the wrong syntax.
#include <iostream>
using namespace std;
int main()
{
int input;
char abjad;
abjad='A';
cout<<"INPUT = ";
cin>>input;
for(int i=1;i<=input;i++){
for(int j=0;j<i;j++){
cout<<abjad;
abjad++;
}
cout<<i+1;
for(int k=0;k<input-i-1;k++){
cout<<abjad;
abjad++;
}
cout<<endl;
}
}
}
Here is your solution:
// ...
for (int i = 0; i < input; i++) {
for (int j = 0; j < i; j++) {
cout << abjad;
abjad++;
}
cout << i + 2;
// ...
I have only changed the first for loop to start with 0 instead of 1 and as a compensation to this the condition changed to i < input instead of <=. Also number output is now cout << i + 2;
This should fix your issue.

Runlength Encoding Algorithm[Data Compression]

I am trying to implement the algorithm RLE with simple input like:
ddddddddddhhhhhhhhhhhhhhhttttttttttttt
code:
#include<iostream>
#include<fstream>
#include<vector>
using namespace std;
int main() {
vector<char> read;
ifstream file;
file.open("file.txt");
if (!file) {
cout << "Unable to open";
}
char v;
while(file>>v) {
read.push_back(v);
}
char x;
int count=0;
for(int i=0; i<read.size(); i++) {
x = read[i];
if(x != read[++i]) {
cout << x << "1";
}
while(x == read[++i]) {
count++;
}
cout << x << count;
count = 0;
}
return 0;
}
The output I am getting is:
d9d1h12h1t10t1
Please help me with the code.
Update: I have updated the question as I have realized few things.
Plus: This code produced no output, is there anything wrong which I am doing wrong?
char o;
char n;
int count=0;
for(int i=0; i<read.size(); i++) {
o = read[i];
n = read[++i];
while(o == n) {
count++;
}
cout << o << count;
if(o != n) {
cout << o << "1";
} count = 0;
}
return 0;
This loop:
char x;
int count=0;
for(int i=0; i<read.size(); i++) {
int j=i;
x = read[i];
if(x != read[++j]) {
cout << x << "1";
}
while(x == read[++j]) {
count++;
}
cout << x << count;
}
Has several errors. First, you should use two indices, i and j. i is going through each element of read, but then j is iterating through a subsequence too. What you want is to go through each element only once, and in each case either print or increase the count. However having a for loop and moving the index inside too is not a very good practice, is rather error-prone. Also you have to cout statements that are do not run at the right time (you don't wan to print something on every iteration, only when the character changes). You could do it with a while loop, or using a simpler structure like:
// If there are no characters finish
if (read.empty()) {
return 0;
}
// Get the first character
char lastChar = read[0];
int count = 1; // We have counted one character for now
// Go through each character (note start from 1 instead of 0)
for(int i = 1; i < read.size(); i++) {
// Get the next char
char newChar = read[i];
// If it is different, print the current count and reset the counter
if (lastChar != newChar) {
cout << lastChar << count;
count = 1;
lastChar = newChar;
} else { // Else increase the counter
count++;
}
}
// Print the last one
cout << lastChar << count;
return 0;

How to print a range of characters from one index to another in a string in C++

I'm working on a lab for school. The goal of the last exercise is to make a program that can scan a string input by the user for any words that suffer from "capslock syndrome" (i.e. words that begin with a lowercase letter and have all uppercase letters, lIKE tHIS). This is what I've got so far:
#include<iostream>
#include<string>
#include<cctype>
using namespace std;
int main()
{
string s("");
int len;
do
{
cout<<"Enter a string. I will check it for \"caps-lock syndrome\"\n";
getline(cin, s);
cout<<endl;
cout<<s<<"\n\n";
len = s.length();
for(int i=0; i<len; i++){
if(islower(s[i])){
for(int j=i+1; j<len; j++){
if(isupper(s[j])){
cout<<s[j];
}
}
}
}
} while(!s.empty());
return 0;
}
What should happen is when the user enters a string like "cAPS lOCK is on" the resulting output should be:
cAPS
lOCK
And then loop back to the start of the program. The problem I'm getting now is that I can't get the full word to print (just the uppercase characters) and I can't get each word to print to its own line like I want to.
Here is code that may help you:
string the_string = "hELLO hOW aRE yOU";
vector<string>v;
string new_string = "";
for (int i = 0; i < the_string.length(); i++)
{
if (the_string[i] != ' ')
{
new_string += the_string[i];
}
else
{
v.push_back(new_string);
new_string = "";
}
}
//Now, the string vector is loaded
for(int i = 0; i < v.size(); i++)
{
if (islower(v[i][0]))
{
int counter = 0;
for (int b = 1; b < v[i].length(); b++)
{
if (isupper(v[i][b]))
{
counter += 1;
}
}
if (counter == v[i].length()-1)
{
cout << v[i]<< " has caps lock syndrome"<< endl;
}
else
{
cout << v[i] << " does not have caps lock syndrome"<< endl;
}
}
else
{
cout << v[i]<< " does not have caps lock syndrome"<< endl;
}
}

Having trouble with arrays

I'm 100% sure my code is incorrectly determining the size of the array
When I put in hello as the input and set strArray[5] it works correctly. But the problem is I don't know how big the size of the input will be so I just put 80 (since that's the max it could be)
Here's my code.
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
using namespace std;
main()
{
string str1;
char strArray[80];
cout << "Enter string: ";
getline(cin, str1);
transform(str1.begin(), str1.end(), str1.begin(), ::tolower);
str1.erase(remove(str1.begin(),str1.end(),' '),str1.end());
for(int i = 0;i < str1.length(); i++)
{
if(str1[i] == ',' || str1[i] == '.')
{
str1.erase(i,1);
}
}
for(int i=0;i<str1.length();i++)
{
strArray[i] = str1[i];
}
char tempChar;
for(int i = 0; i < (sizeof(strArray)/sizeof(*strArray))-1; i++)
{
for(int j = 0; j < (sizeof(strArray)/sizeof(*strArray)-1); j++)
{
if(strArray[j+1] < strArray[j])
{
tempChar = strArray[j];
strArray[j] = strArray[j+1];
strArray[j+1] = tempChar;
}
}
}
cout << strArray << endl;
return 0;
}
You can just make strArray a string. Or, if you must use a char array, you should dynamically allocate the char array with char *strArray = new char[str1.length()]. In this case, don't forget to delete [] strArray; when done.