Having trouble with arrays - c++

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.

Related

Is there a way I can fix this issue with length counter function?

I have to find the length of an array of characters using a function that uses the pointer notation and, for some reason, I get 23 but the result should be 5.
Here is the code I built:
#include <iostream>
using namespace std;
int length(char *N)
{
int length = 0;
char* S = N;
for (; *S != '\0'; S++);
for (; *N != *S; N++)
{
length++;
}
return length;
}
int main()
{
char A[5];
char *N;
N = A;
cout << "please enter the charecters you desire" << endl;
for (int i = 0; i <=4; i++)
{
cin >> A[i];
}
cout<<length(N);
}
You don't need two loops.
And note that you have to leave a space in the array (the last element) to fill it by '\0'.
Hence by the two notes and if you want to use five characters excluding the '\0', your code will be as follows
#include <iostream>
size_t length(char *N){
size_t length = 0;
for (; *N != '\0'; N++){
length++;
}
return length;
}
int main()
{
char A[6];
std::cout << "please enter the characters you desire\n";
for (int i = 0; i < 5; i++){
std::cin >> A[i];
}
A[5] = '\0';
std::cout << length(A);
}

How to store rows of chars from the user input to a dynamically allocated jagged 2d char array in C/C++?

Given that each row of char is terminated by the 'E' character and the final row is terminated by the 'T' character. I am struggling to print out the rows of chars given by the user excluding the terminated characters. It is obligatory to use one of the malloc(), calloc(), realloc(), and free() functions.
Sample input and output could be like this:
Input
Output
A B C E V F E K T
A B C V F K
My attempt:
#include <iostream>
#include <sstream>
#include <string>
#include <math.h>
#include <vector>
#include <stdio.h>
using namespace std;
int main()
{
char c;
int rowsize = 0 ,colsize = 0;
char** chararr;
chararr = (char**)malloc(sizeof(char*));
vector<int> colsizes;
char chars[20];
do {
cin >> c;
colsize++;
for(int i=0; i<colsize;i++) {
chars[i] = c;
}
if ( c == 'E') {
++rowsize;
colsizes.push_back(colsize);
chararr = (char**)realloc(chararr,rowsize*sizeof(char*));
for (int i = 0; i < rowsize; ++i){
*(chararr + i) = (char*)malloc(colsizes[i] * sizeof(char));
for (int j = 0; j < colsizes[i]; ++j) {
chararr[i][j] = chars[j];
}
}
colsize = 0 ;
continue;
}
}while(c != 'T');
colsizes.push_back(colsize);
for (int i = 0; i < rowsize; ++i){
for (int j = 0; j < colsizes[i]; ++j) {
std::cout << chararr[i][j] << " ";
}
std::cout << endl;
}
}
Here is the one of the c++ way that you can do,
string line;
while (getline(cin, line)) {
stringstream str(line);
string word;
while (str >> word) {
if (word == "E") {
break;
}
cout << word << " ";
}
cout << endl;
}
here another way on CPP, this way you need to enter letter by letter and in the end its print, if you get the whole line at once change the while loop to std::getline()
#include <iostream>
#include <vector>
int main()
{
char c;
std::vector<char> vec;
while(c != 'T')
{
std::cin >> c;
vec.push_back(c);
}
for(auto& c : vec)
{
if(c == 'E')
{
std::cout << "\n";
} else
{
std::cout << c << " ";
}
}
return 0;
}
Your code is a mix of C++ and C. So I am going to go ahead and assume it is C++. I'll write C++ suggestions followed by C-style implementation remarks.
vector<vector<char>> v;
do {
v.push_back(vector<char>{});
do {
cin >> c;
v.push_back(c);
} while(c != 'E' && c != 'T');
} while(c != 'T');
for(std::size_t i = 0; i<v.size(); i++) { for(std::size_t j = 0; j<v[i].size() - 1; j++) {std::cout << v[i][k] << " "} }
This is an ugly C++ solution that's expected to work. j<v[i].size() - 1 to skip terminated characters.
Now, malloc and free are mandatory meaning this homework should be written in C-style. Do not use vectors, vectors are part of C++ not C. we need to write this in a C style. Since it is your homework, I'll not post the entire solution, however, I'll raise some remarks to help you get there.
Logic
The first issue in your code is
colsize++;
for(int i=0; i<colsize;i++) {
chars[i] = c;
}
This will override the row with the last character read, E in your case for every row. This will become:
chars[colsize] = c;
colsize++;
Malloc
We have to store your characters in a matrix that we dynamically allocate (we cannot use vectors). Your matrix chararray, is not properly allocated. This will result in a lot of headaches. The below is wrong
int rowsize = 0, colsize = 0;
char **chararr;
chararr = (char **)malloc(sizeof(char *));
This is how you do it it:
scanf("%d %d", &r, &c);
char** chararr = malloc(sizeof(char*) * r);
for (i = 0; i < r; i++)
chararr[i] = malloc(c);
Free
Now your matrix of chars is allocated. Since it was allocated dynamically we need to free it manually. Always remember if you have n malloc in your code, you expect to have n frees. So, there is no memory leak. Freeing a matrix will be in the reverse way it was allocated. Why? We need to free its underlying pointers for every row the way we allocated them.
   
for (i = 0; i < r; i++)
        free(chararr[i]);
         
free(chararr);

How can I compare the elements in a vector?

I took a look online and none of the answers solves the problem I have comparing the elements from a vector.
I tried implementing a bool function but the problem is the same.
I am pretty new in c++ so please be patient!
PART2: First of all thank you.
So I changed my programm and created a bool function, the problem is now that it doesn get recognised before 5-6 tries.
#include <iostream>
#include <vector>
#include <time.h>
#include <stdlib.h>
#include <string>
using namespace std;
vector<int> input, compareMe, randomNumbers;
const unsigned int MAX_VEKTORSTELLEN = 5;
const unsigned int UPPER_GRENZE = 49;
const unsigned int LOWER_GRENZE = 1;
unsigned int i, j;
string output;
int random, anzahlRichtige, eingabe;
bool isEqual = false;
string lotto(vector<int>)
{
if (input[i] < LOWER_GRENZE || input[i] > UPPER_GRENZE)
{
output = "Die Zahlen muessen zwischen 1 und 49 liegen! \n";
input.pop_back();
}
else if (input.size() != MAX_VEKTORSTELLEN)
output = "Es muessen 6 Zahlen uebergeben werde! \n";
else if (isEqual == true)
output = "Es duerfen keine doppelten Zahlen vorkommen! \n";
else
for (i = 0; i <= MAX_VEKTORSTELLEN; i++)
srand((unsigned)time(NULL) <= UPPER_GRENZE && (unsigned)time(NULL) > 0);
random = rand();
randomNumbers.push_back(random);
return output;
}
bool compare()
{
compareMe = input;
for (i = 0; i < input.size(); i++)
for (j = 0; j < compareMe.size(); j++)
if (compareMe[j] == input[i])
isEqual = true;
return isEqual;
}
int main()
{
cout << "insert 6 numbers: ";
while (cin >> eingabe)
{
input.push_back(eingabe);
lotto(input);
compare();
cout << output;
for (i = 0; i < input.size(); i++) //Debug
cout << input[i] << ", ";
continue;
}
for (i = 0; i < input.size(); i++)
cout << input[i];
system("pause");
return 0;
}
From line 34 to line I didn´t finish to code but doesn´t really matter because I got stuck before.
All your loops in lotto are wrong. You go one past the end of your containers.
for (i = 0; i <= input.size(); i++)
// ^ !!!
It should be <.
You got this right in main.

Run length encoding in C++

#include <iostream>
#include <string>
#include <vector>
using namespace std;
string compression(const string & str){
int i = str.size();
string letters;
letters[0] = str[0];
for (int j = 0; j < i; ++j){
int count = 1;
while (str[j] == str[j+1]){
count++;
j++;
}
letters.push_back('0' + count);
letters.push_back(str[j]);
}
return letters;
}
int main(){
string input;
char c;
try {
cout << "Enter the data to be compressesed: "<< endl;
cin >> input;
for (int z = 0; z < input.length(); ++z){
c = input.at(z);
}
if (!(c >= 'a' && c <= 'z')){
throw runtime_error("error: invalid input");
}
}
catch (runtime_error& excpt){
cout << excpt.what() <<endl;
return 0;
}
cout << "The compressed data is " << compression(input) << endl;
return 0;
}
The expected output is , repeated for each run of characters. Here is the amount of times is repeated in sequence.
Some examples:
aaeeeeae = 2a4e1a1e
rr44errre = invalid input
eeeeeeeeeeeeeeeeeeeee = 21e
the code works properly only if the character is repeated consecutively 9 times or less. for values of 10 and more the input is other symbols.
For example it stays blank for 10, so if input is 'aaaaaaaaaabb',output just would be 'a2b' instead of '10a2b'. For 11 its outputs ';',
so if input is 'aaaaaaaaaaabb', output is ';a2b' for some reason.
So my question is, how do i make the pushback work for all numbers and not just from 0-9?
Thank you for your time if u've gotten to here. ^^
If you can use c++11 or newer your function compression could look like:
string compression(const string & str){
int i = str.size();
string letters;
for (int j = 0; j < i; ++j){
int count = 1;
while (str[j] == str[j+1]){
count++;
j++;
}
letters += std::to_string(count);
letters.push_back(str[j]);
}
return letters;
}

C++ - Adding Spaces to String

Hey so I am trying to write a simple program that adds spaces to a given string that has none in C++ here is the code I have written:
#include <iostream>
#include <string>
using namespace std;
string AddSpaceToString (string input)
{
const int arrLength = 5;
int lastFind = 0;
string output;
string dictionary[arrLength] = {"hello", "hey", "whats", "up", "man"};
for (int i = 0; i < input.length(); i++)
{
for (int j = 0; j < arrLength; j++)
{
if(dictionary[j] == input.substr(lastFind, i))
{
lastFind = i;
output += dictionary[j] + " ";
}
}
}
return output;
}
int main ()
{
cout << AddSpaceToString("heywhatshelloman") << endl;
return 0;
}
For some reason the output only gives hey whats and then stops. What is going on I can't seem to make this very simple code work.
After reading "hey" and "whats", the value of i is more than the length of "hello" and hence no such substring exists for the code input.substr(lastFind, i).
You should check for the length of possible substring (dictionary[j]) and not i.
input.substr( lastFind, dictionary[j].size() )
Also you will have to change:
lastFind += dictionary[j].size();
So the if loop becomes:
if(dictionary[j] == input.substr(lastFind, dictionary[j].size() ))
{
lastFind += dictionary[j].size();
output += dictionary[j] + " ";
}
this works
#include <iostream>
#include <string>
using namespace std;
string AddSpaceToString (string input)
{
const int arrLength = 5;
unsigned int lastFind = 0;
string output;
string dictionary[arrLength] = {"hello", "hey", "whats", "up", "man"};
for (int j = 0; lastFind < input.size() && j < arrLength; ++j)
{
if(dictionary[j] == input.substr(lastFind, dictionary[j].size()))
{
lastFind += dictionary[j].size();
output += dictionary[j] + " ";
j = -1;
}
}
return output;
}
int main ()
{
cout << AddSpaceToString("heywhatshelloman") << endl;
return 0;
}