C putting floats in a 2D array puts random values - c++

I take input from the user, calculate the number of rows and columns needed and put all the numbers in an array but it puts seemingly random values, it also duplicates some values i want to take the input from the user and put all the numbers in 2d array in order to do matrix operations
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <stdlib.h>
#include <string.h>
using namespace std;
#define max_input_limit 99
float matrix_1[100][100];
float matrix_2[100][100];
float result[100][100];
int rows_1 = 0;
int cols_1 = 0;
void str_to_array1(char str[max_input_limit])
{
// sample input: [1 2 3, 4 5 6, 7 8 9]
// count number of commas
int rows = 1;
for (int i = 0; i < strlen(str); i++)
{
if (str[i] == ',')
rows++;
}
rows_1 = rows;
// count number of spaces before first comma
int cols = 1;
for (int i = 0; str[i] != ','&&i<strlen(str); i++)
{
if (str[i] == ' ')
{
cols++;
}
}
cols_1 = cols;
//remove all commas and brackets from str
for (int i = 0; i < strlen(str); i++)
{
if (str[i] == ',' || str[i] == '[' || str[i] == ']')
{
str[i] = ' ';
}
}
// fill 2D array
float arr[100][100];
for (int i = 0; str[i] != '\0'; i++)
{
for (int r = 0; r <= rows; r++)
{
for (int c = 0; c < cols; c++)
{
if (str[i] != ' ' && str[i+1] != NULL)
{
arr[r][c] = atof(&str[i]);
matrix_1[r][c] = arr[r][c];
cout << matrix_1[r][c]<<" ";
//if (arr[r][c] == rows+r)
//cout << ",";
i++;
}
}
}
}
}
void str_to_array2(char str[max_input_limit])
{
// sample input: [1 2 3, 4 5 6, 7 8 9]
// count number of commas
int rows = 1;
for (int i = 0; i < strlen(str); i++)
{
if (str[i] == ',')
rows++;
}
rows_1 = rows;
// count number of spaces before first comma
int cols = 1;
for (int i = 0; str[i] != ','; i++)
{
if (str[i] == ' ')
cols++;
}
cols_1 = cols;
//remove all commas and brackets from str
for (int i = 0; i < strlen(str); i++)
{
if (str[i] == ',' || str[i] == '[' || str[i] == ']')
{
str[i] = ' ';
}
}
// fill 2D array
float arr2[100][100];
for (int i = 0; str[i] != '\0'; i++)
{
for (int r = 0; r <= rows; r++)
{
for (int c = 0; c < cols; c++)
{
if (str[i] != ' ' && str[i + 1] != NULL)
{
arr2[r][c] = atof(&str[i]);
matrix_2[r][c] = arr2[r][c];
cout << matrix_2[r][c]<<" ";
//if (arr[r][c] == rows+r)
//cout << ",";
i++;
}
}
}
}
}
void add(float result[100][100], float matrix_1[100][100], float matrix_2[100][100])
{
cout << "[";
for (int r = 0; r < rows_1; r++)
{
for (int c=0; c < cols_1; c++)
{
result[r][c] = matrix_1[r][c] + matrix_2[r][c];
cout << result[r][c] << " ";
}
}
cout << "]";
}
int main()
{
char str[99];
char str2[99];
cin.getline(str, 99);
str_to_array1(str);
cin.ignore();
cin.getline(str2, 99);
str_to_array2(str2);
}
When i put
[1 2 33, 4 55 6]
I get output
[1 2 33 3 4 55 5 6 ]

Related

Printing hollow square with array

I'm trying to print a hollow square. I currently have the top, bottom, and left borders drawn but for some reason cannot get the right side to draw in the correct place. I'm sure its a simple fix but I'm new to this so sorry for noobness.
int main()
{
const int boardX = 10;
const int boardY = 10;
char gameBoard[boardX][boardY];
for (int i = 0; i != boardX; i++)
{
for (int k = 0; k != boardY; k++)
{
if (i == 0 || i == 9 || k == 0 || k == 9)
{
gameBoard[i][k] = '*';
cout << gameBoard[i][k];
}
}
cout << "\n";
}
system("pause");
return 0;
}
You forgot to print spaces to make the square hollow:
int main()
{
const int boardX = 10;
const int boardY = 10;
char gameBoard[boardX][boardY];
for (int i = 0; i != boardX; i++)
{
for (int k = 0; k != boardY; k++)
{
if (i == 0 || i == 9 || k == 0 || k == 9)
{
gameBoard[i][k] = '*';
cout << gameBoard[i][k];
}
else
{
gameBoard[i][k] = ' ';
cout << gameBoard[i][k];
}
}
cout << "\n";
}
return 0;
}
Note: I followed your style to make the changed part stand out, but normally you would separate the construction of the board and printing it to the screen into separate code blocks/functions.

how to extract the coefficients and exponent of a polynomial as string

hello my problem is that i have to extract the coefficients and exponent of a polynomial given by the user.
when i tried my code it just worked for the coefficient, and for the exponent it gives me a zero. p.s a is just for testing
int main() {
char x[10];
char y[10];
char a[100] = "53x2+4x^3";
for (int i = 0; a[i] != '+'; i++)
{
if (a[i] != 'x')
{
x[i] = a[i];
}
}
for (int i = 0; a[i] != '+'; i++)
{
if ((a[i] == 'x') && (a[i + 1] == '^')) {
y[i] = a[i + 2];
}
}
double w;
int z;
w = atof(x);
z = atoi(y);
cout << w << endl;
cout << z << endl;
return 0;
}
You need to initialize your coefficient and exponent buffers with null terminators so that they are properly null terminated when the output console reads them.
#include <iostream>
using namespace std;
int main() {
char x[10] = {'\0'};
char y[10] = {'\0'};
char a[100] = "53x^2+4x^3";
for (int i = 0, j = 0; a[i] != '+'; i++)
{
if (a[i] != 'x')
{
x[j] = a[i];
j++;
}
}
for (int i = 0, j = 0; a[i] != '+'; i++)
{
if ((a[i] == 'x') && (a[i + 1] == '^')) {
y[j] = a[i + 2];
j++;
}
}
double w;
int z;
w = atof(x);
z = atoi(y);
cout << w << endl;
cout << z << endl;
return 0;
}

Error for c++ example

I want to input alphabet to binary code, and output the alphabet from generated binary code.
Example
1 --> a
01 --> b
001 --> c
0001 --> d
00001 --> e
000001 --> f
a => 1
b => 01
c => 001
d => 0001
e => 00001
-------------Encode.cpp--------------------
#include "Encode.h"
Encode::Encode()
{
}
Encode::~Encode()
{
}
void Encode::inputWord()
{
cout << "Input word: ";
cin.getline(word, 255);
return;
}// User input a word
char * Encode::getBuf(void)
{
return buffer;
}// return buffer to Decode::setBuf(char* buf)
void Encode::printEncResult()
{
int size = strlen(word);
int buffersize = 0;
cout << "Encoding result" << endl; // print similar binary
for (int i = 0; i < size; i++)
{
if (word[i] == 'z')
{
for (int j = 0; j < 25; j++)
{
cout<<buffer[buffersize++];
}
}
else
{
int len = (int)word[i] - (int)'a';
for (int j = 0; j < len; j++)
{
cout<<buffer[buffersize++];
}
cout << buffer[buffersize++];
}
}
}// output similar binary
int Encode::encodeWord(void)
{
int buffersize = 0;
int size = strlen(word);
for (int i = 0; i < size; i++)
{
if (word[i] == 'z')
{
for (int j = 0; j < 25; j++)
{
buffer[buffersize++] = '0';
}
}
else
{
int len = (int)word[i] - (int)'a';
for (int j = 0; j < len; j++)
{
buffer[buffersize++] = '0';
}
buffer[buffersize++] = '1';
}
}
return 0;
}// change word to similar binary
--------Decode.cpp-------------
#include "Decode.h"
Decode::Decode()
{
}
Decode::~Decode()
{
}
void Decode::setBuf(char * buf)
{
int i = 0;
int size = 0;
while (*(buf + i) == '1' || *(buf + i) == '0')
{
i++;
}
size = i;
for(int i = 0; i < size; i++)
{
buffer[i] = buf[i];
}
return;
}// set buffer from Encode::getBuf(void)
void Decode::printWord() // print similar binary
{
int i = 0;
int size = 0;
int check = 1;
while (check)
{
if (word[i] >= 'a' && (int)word[i] <= 'z')
{
i++;
size = i;
}
else
check = 0;
}
cout << "Decoding result" << endl;
for (int i = 0; i < size; i++)
{
if (word[i] >= 'a' && (int)word[i] <= 'z') // **this part is also strange** I can not shoten the code.
cout<<word[i];
}
cout << endl;
}
int Decode::decodebin(vector<char> buffer)
{
int buffersize = 0;
int check = 0;
int size = 0;
int i = 0;
char printval = 'a';
while (buffer[i] == '1' || buffer[i] == '0')
{
i++;
}
size = i;
for (int j = 0; j < size; j++) // nested loop does not work. I want save words in order
{
for (i = 0; i < size; i++)
{
if (buffer[i] == '0')
++printval;
else
{
word[j] = printval; // In this part, word[0] does not have any value.
printval = 'a';
}
}
}
return 0;
}
In this code, I want save values in order, but word[0] does not have any value. Moreover, If I input 'bb' then, 'bbbb' saved ins word array.
There are some problems and consideration you need to take care of:
as Fei Xiang said in the comments don't use magic numbers, use characters since you have a character array.
int printWord function you actually get the word and print the same word, there is no conversion as your problem statement. your didn't take buffer into account.
you are using some data validation to get your array size, this could end up a disaster(UB). you need to pass your array size to your function or use std::vector(Recommended).
in this statement if ((int)word[i] >= 97 || (int)word[i] <= 122) as I said don't use magic number and || should be change to && otherwise you end up in an infinity loop.
Anyway by keeping your approach(using array) and function signature here's what you can do :
int Decode::decodebin(void)
{
int buffersize = 0;
int check = 0;
int size = 0;
int i = 0;
char printval = 'a';
while(buffer[i] == '1' || buffer[i] == '0')
{
i++;
size = i;
}
for(int i = 0; i < size; i++)
{
if(buffer[i] == '0')
++printval;
else
{
cout << printval;
printval = 'a';
}
}
return 0;
}
void Decode::printWord()
{
int i = 0;
int size = 0;
int check = 1;
while(check)
{
if(word[i] >= 'a' && word[i] <= 'z')
{
i++;
size = i;
}
else
check = 0;
}
cout << "Decoding result" << endl;
for(int i = 0; i < size; i++)
{
int distance = word[i] - 'a';
for(int j = 0; j < distance; ++j)
cout << '0';
cout << '1';
}
cout << endl;
}
EDIT BASED ON OP REQUIREMENT IN COMMENTS:
using std::vector you can implement your needs like this :
#include <iostream>
#include <vector>
class Decode
{
public:
void decodebin(std::vector<char> buffer)
{
char printval = 'a';
for(unsigned int i = 0; i < buffer.size(); i++)
{
if(buffer[i] == '0')
++printval;
else
{
word.push_back(printval);
printval = 'a';
}
}
}
void printWord(void)
{
for(auto iter = word.begin(); iter != word.end(); ++iter)
std::cout << *iter;
std::cout << std::endl;
}
private:
std::vector<char> word;
};
int main()
{
Decode decoder;
std::vector<char> buffer = {'0', '1', '0', '0', '0', '0', '1', '0', '0', '0', '1'};
decoder.decodebin(buffer);
decoder.printWord();
return 0;
}
Here decodebin stores the given input into word member variable of Decode class. Then printWord function print word values on the screen.
std::vector has all the power of C-style array and it's nicer and easier to use. You can retrieve it's size whenever you want and you don't have to worry about the memory it's allocating.

whenever I try to run this code the break appears or stops working

what I want to do is :
Input a sentence from the user. Use full stop, space and comma as word separators. Each word should be stored in a 2D array whose columns vary in size and each row stores one word as a NULL terminated string.
For example, if the user inputs:
Hello how are you?
It should be stored as:
H E l l o NULL
h o w NULL
a r e NULL
y o u ? NULL
so whenever I try to run my code either this error appears
Exception thrown at 0x00832605 in Project109.exe: 0xC0000005: Access violation writing location 0xFDFDFE03.
or the program stops working.major problem is in
ptr[i][j] = str1[j];
`
char str1[20];
cin.get(str1, 20);
int len, sum = 0;
len = strlen(str1);
int i = 0;
while (str1[i] != '\0')
{
if (str1[i] == ' ' || str1[i] == '.' || str1[i] == ',' || str1[i] == '?' || str1[i] == ';')
{
sum = sum + 1;
}
i++;
}
char **ptr;
ptr = new char*[sum];
for (int i = 0; i < sum; i++)
{
ptr[i] = new char[20];
}
for (int i = 0; i < sum; i++)
{
for (int j = 0; j < 20; j++)
{
ptr[i][j] = '\0';
}}
for (int i = 0; i < sum; i++)
{
for (int j = 0; j < 20; j++)
{
if (str1[j] == ' ' || str1[j] == '.' || str1[j] == ',' || str1[j] == '?' || str1[j] == ';')
{
i++;
}
else
{
ptr[i][j] = str1[j];
}
}
}
for (int i = 0; i < sum; i++)
{
int j = 0;
while (ptr[i][j] != '\0')
{
cout << ptr[i][j];
j++;
}
}
for (int i = 0; i < sum; i++)
{
delete[] ptr[i];
}
delete[] ptr;
system("pause");
return 0;}
`
You are indexing out of range, and hitting memory with fence bytes containing 0xFD.
Consider the loop here
for (int i = 0; i < sum; i++)
{
for (int j = 0; j < 20; j++)
{
if (str1[j] == ' ' || str1[j] == '.' || str1[j] == ',' || str1[j] == '?' || str1[j] == ';')
{
i++;
}
else
{
ptr[i][j] = str1[j];
}
}
}
If i is already at (or near) it's maximum value, in the inner loop you might increment it one or more times before reaching ptr[i][j] = str1[j];. At that time i might be way more than sum.
better solution but output is not that as required :
{ char str1[20];
cin.get(str1, 20);
int len, sum = 0;
len = strlen(str1);
int i = 0;
while (str1[i] != '\0')
{
if (str1[i] == ' ' || str1[i] == '.' || str1[i] == ',' || str1[i] == '?' || str1[i] == ';')
{
sum = sum + 1;
}
i++;
}
char **ptr;
ptr = new char*[sum];
for (int i = 0; i < sum; i++)
{
ptr[i] = new char[len];
}
for (int i = 0; i < sum; i++)
{
for (int j = 0; j < len; j++)
{
if (str1[j] == ' ' || str1[j] == '.' || str1[j] == ',' || str1[j] == '?' || str1[j] == ';')
{
ptr[i][j] = str1[j];
i++;
}
else
{
ptr[i][j] = str1[j];
}
}
}
for (int i = 0; i < sum; i++)
{
for (int j = 0; j < len; j++)
{
cout << ptr[i][j];
}
cout << endl;
}
for (int i = 0; i < sum; i++)
{
delete[] ptr[i];
}
delete[] ptr;
system("pause");
return 0;}

Switching letters in words C++

#include <iostream>
#include <cstring>
using namespace std;
int main() {
char main[10000] = {0};
cin.getline(main, 10000);
char clone [10000] = {0};
int n;
cin >> n;
int counter = 0;
int counter2 = 0;
for (int z = 0 ; z < strlen(main); z++) {
if (main[z] == '.' || main[z] == ',' || main[z] == ' ' || main[z] =='"' ||
main[z] == '!' || main[z] == '?' || main [z] == ';')
counter2++;
}
if (counter2 == 0) {
if (strlen(main) < n) {
n = n % strlen(main);
}
int b = strlen(main);
for (int x = b - n; x < b ; x++) {
cout << main[x];
}
for (int y = 0; y < x - n; y++) {
cout << main[y];
}
}
for (int i = 0; i < strlen(main); i++) {
clone[counter] = main[i];
if(main[i] == '.' || main[i] == ',' || main[i] == ' ' || main[i] =='"' ||
main[i] == '!' || main[i] == '?' || main [i] == ';') {
int a = strlen(clone);
if (counter < n) {
n = n % counter;
}
for (int x = a - n - 1; x < a - 1; x++) {
cout << clone[x];
}
for (int y = 0; y < x - n; y++) {
cout << clone[y];
}
cout << main[i];
counter = 0;
for (int z = 0; z < a; z++) {
clone[z] = '\0';
}
}
else {
counter++;
}
}
return 0;
}
I'm working on a project that switches letters in words. For example the word funny when n = 3 will output nnyfu. It just moves all letters n-times. However when I try to do this with a long sentence containing a character different than a letter and follow it with another char of the same type (for example a coma followed by space) the program seems to crash. I'm wondering if anyone can help me with this because I've been pulling my hair out all day long. Also it mustn't be necessary for an input with a couple of words to end with a char different than a letter but I can't seem to figure it out too (for example inputting "Hello my friends" and n = 3 it will output "lloHe ym).