From user input such as:
>~d
alg
^%r
what would be the best way to create a square char matrix with each of the entered values assigned to the corresponding element? e.g. in this case charArray[0][0] would be '>' and charArray[2][1] would be '%' etc.
I tried the following using getchar(); however, I was having all kinds of problems with the '\n' that was left behind and figured there is probably an entirely different way of effecting this that was much better.
char matrix[MAX][MAX];
char c;
int matSize;
std::cin >> matSize;
for (int i = 0; i < matSize; ++i)
{
int j = 0;
while ((c = getchar()) != '\n')
{
matrix[i][j] = c;
++j;
}
}
As you're using C++, why not use std::cin and std::string to read a hole line. Probably not the best option, but it works.
for (int i = 0; i < matSize; ++i)
{
std::cin >> in;
if (in.length() < matSize)
{
printf("Wrong length\n");
return 1;
}
for (int j = 0; j < matSize; j++)
matrix[i][j] = in[j];
}
Since every matrix[i] is a char array with a fixed size you can easily use std::istream::getline:
#include <iostream>
#include <istream>
#define MAX 10
int main()
{
char matrix[MAX][MAX];
char c;
int matSize;
std::cin >> matSize;
std::cin >> c; // don't forget to extract the first '\n'
if(matSize > MAX){ // prevent segmentation faults / buffer overflows
std::cerr << "Unsupported maximum matrix size" << std::endl;
return 1;
}
for(int i = 0; i < matSize; ++i){
std::cin.getline(matrix[i],MAX); // extract a line into your matrix
}
std::cout << std::endl;
for(int i = 0; i < matSize; ++i){
std::cout << matrix[i] << std::endl;
}
return 0;
}
Related
I want a program that asks the number of rows and columns of the multidimensional array and then using For loop iterate values in the array.
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n, m, x;
int a[n][m];
cin>>n>>m;
for(int i; i<n ; i++)
{
for(int j; j<m ; j++)
{
cout<<"Enter the values";
cin>>x;
a[i][j] = x;
}
}
return 0;
}
here it gets error:
main.cpp|6|warning: 'm' is used uninitialized in this function [-Wuninitialized]|
main.cpp|6|warning: 'n' is used uninitialized in this function [-Wuninitialized]|
You can't declare the array unknown size. You must do it dynamically.
#include <iostream>
using namespace std;
int main()
{
int n = 0, m = 0;
//. Get the matrix's size
while (true)
{
cout << "Input the row count: "; cin >> n;
cout << "Input the column count: "; cin >> m;
if (n < 1 || m < 1)
{
cout << "Invalid values. Please retry." << endl;
continue;
}
break;
}
//. Allocate multi-dimensional array dynamically.
int ** mat = new int *[n];
for (int i = 0; i < n; i++)
{
mat[i] = new int[m];
}
//. Receive the elements.
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
cout << "Input the element of (" << i + 1 << "," << j + 1 << "): ";
cin >> mat[i][j];
}
}
//. Print matrix.
cout << endl << "Your matrix:" << endl;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
cout << mat[i][j] << "\t";
}
cout << std::endl;
}
//. Free memories.
for (int i = 0; i < n; i++)
{
delete[] mat[i];
}
delete[] mat;
return 0;
}
If you like to use stl, it can be simple.
#include <iostream>
#include <vector>
using namespace std;
using ROW = vector<int>;
using MATRIX = vector<ROW>;
int main()
{
int n = 0, m = 0;
MATRIX mat;
cin >> n >> m;
for (int i = 0; i < n; i++)
{
ROW row;
row.resize(m);
for (int j = 0; j < m; j++)
{
cin >> row[j];
}
mat.push_back(row);
}
for (auto & row : mat)
{
for (auto & iter : row)
{
cout << iter << "\t";
}
cout << endl;
}
return 0;
}
Some comments.
Please never use #include<bits/stdc++.h>. This is a none C++ compliant compiler extension
Please do not use using namespace std;. Always use fully qualified names.
For the above to statements you will find thousands of entries here on SO
In C++ you cannot use VLAs, Variable Length Array, like int a[n][m];. This is not part of the C++ language
You should not use C-Style arrays at all. Use std::array or, for your case std::vector.
Use meaningful variable names
Write comments
Always initialize all variables, before using them!!!
And, last but not least. You will not learn C++ on this nonesens "competition - programming" sites.
And one of many millions possible C++ solutions (advanced) could look like that:
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
int main() {
// Read the dimension of the 3d data
if (unsigned int numberOfRows{}, numberOfCoulmns{}; (std::cin >> numberOfRows >> numberOfCoulmns) and (numberOfRows > 0u) and (numberOfCoulmns > 0u)) {
// Define a vector with the requested size
std::vector<std::vector<int>> data(numberOfRows, std::vector<int>(numberOfCoulmns, 0));
// Read all data
std::for_each(data.begin(), data.end(), [&](std::vector<int>& col) mutable
{ auto it = col.begin(); std::copy_n(std::istream_iterator<int>(std::cin), numberOfCoulmns, it++); });
// Show debug output
std::for_each(data.begin(), data.end(), [](std::vector<int>& col)
{std::copy(col.begin(), col.end(), std::ostream_iterator<int>(std::cout, "\t")); std::cout << '\n'; });
}
else std::cerr << "\nError: Invalid input given\n\n";
return 0;
}
I am again here with this query.
In the following code, I initialize my matrix with all values equals zero and after it, I write this matrix in a text file. Now I want to read that matrix from the file and put all the values in another matrix named arr1[][] and when I print it on the screen I got a blank screen why?
Please help me thanks in advance.
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
int main()
{
int n = 10;
int m = 10;
int arr[10][10];
int arr1[10][10];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
{
arr[i][j] = 0; // here i initialized my matrix with all values zero.
}
ofstream fout;
fout.open("array.txt");
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
fout << arr[i][j]; // here i write it into the file
}
cout << endl;
}
fout.close();
ifstream fin;
fin.open("array.txt");
if (!fin)
{
cerr << std::strerror(errno) << "\n"; // handle open errors
}
fin >> n >> m;
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
{
fin >> arr[i][j]; // now here i read the matrix and put it into the
// different matrix.
arr1[i][j] = arr[i][j];
}
fin.close();
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
cout << arr1[i][j]; // when i print it to the screen i got black screen
// but i wants
// a matrx which written in the file.
}
cout << endl;
}
return 0;
}
so I know how to use cin.get() and how to use buffers or so I thought. Here is a sample program which gets n(number or rows) and m(number of columns) for a table. Then it gets n*m characters, saves them in an array and outputs them:
#include <bits/stdc++.h>
using namespace std;
int n, m;
char in;
char a[100][100];
int main()
{
cin >> n >> m;
for(int i = 0;i < n; ++i)
{
for(int j = 0;j < m; ++j)
{
cin.get(in);
a[i][j] = in;
if(j == m - 1)
cin.get();
}
}
for(int i = 0;i < n; ++i)
{
for(int j = 0;j < m; ++j)
cout <<a[i][j];
cout << endl;
}
return 0;
}
This program seems to count some chars as end of lines. Can someone fix that and explain me. Thank you in advance!
When you enter n and m, cin.get() will start immediately at the char following the number, which could be a space or a new line. There might therefore be a shift between the input you expect and the input that you get. This causes every m chars to be ignored ieven if not a newline, and converseky, some newlines to be read instead of another char.
After your number extraction, it would be safer to cin.ignore() chars until the first new line.
Similarly, check for every nth char that you skip, if it is the newline that you expect.
You have to use cin if you do not want endl and space characters;
Just replace cin.get() with cin>>
#include <bits/stdc++.h>
using namespace std;
int n, m;
char in;
char a[100][100];
int main()
{
cin >> n >> m;
for(int i = 0;i < n; ++i)
{
for(int j = 0;j < m; ++j)
{
cin>>in;
a[i][j] = in;
}
}
for(int i = 0;i < n; ++i)
{
for(int j = 0;j < m; ++j)
cout <<a[i][j];
cout << endl;
}
return 0;
}
The assignment is to search for a word inside a matrix (only left to right) by putting the word and starting point in the command line and return true if the word is there and false if it is not. Unfortunately, I continue to recieve a segmentation fault msg. Any help is greatly appreciated, thanks!
#include <iostream>
#include <vector>
#include <sstream>
#include <string>
using namespace std;
int main(int argc, char *argv[]){
for(int i = 0; i < argc; i++){
cout << argv[i] << " ";
}
char word;
argv[1] = &word;
stringstream ss;
string sWord;
ss << word;
ss >> sWord;
int startRow = atoi(argv[2]);
int startCol = atoi(argv[3]);
int x, y;
cin >> x >> y;
cout << x << y << endl;
vector < vector < char > > matrix;
matrix.resize(x);
for(int i = 0; i < matrix.size(); i++){
matrix.resize(y);
for(int k = 0; k < matrix.size(); k++){
cin >> matrix[i][k];
}
}
for(int i = 0; i < strlen(argv[1]); i++){
if(matrix[startRow][startCol + i] != sWord[i]){
return false;
}
else{
return true;
}
}
}
You are calling strlen() on the address of a single char:
char word;
argv[1] = &word;
...
for(int i = 0; i < strlen(argv[1]); i++){
strlen() requires a null-terminated array of chars, since it only stops at the null-terminator '\0'.
Since the variable "word" is never actually set to anything, your char variable will not have a null-terminator, so strlen() will continue until it reaches a '\0' in memory, which in this case, seems to run beyond your program stack ("word" is a local stack variable, so its address points to your program stack).
I am not sure why you are assigning argv[1] to the address of a char variable, but this should answer your question on why your program is terminating unexpectedly.
You are not initializing your matrix properly:
Instead of
for (int i = 0; i < matrix.size(); i++) {
matrix.resize(y);
your probably meant to write
for (int i = 0; i < matrix.size(); i++) {
matrix[i].resize(y); //resizze "inner" vector
I need to create global n fields of 20 characters in c++ 11 as simple as possible.
#include <iostream>
using namespace std;
char(*a)[20];
int main(){
int n;
do{
cout << "N= ";
cin >> n;
} while (n<1);
a[20] = new char[n][20];
for (int i = 0; i<n; i++) cout << a[i] << endl;
delete[] a;
return 0;
}
Is this code correct? By correct I mean is this n fields/strings of 20 chars.
I want to make sure I don't write in random memory parts.
The array a has to be global because I use it in some custom functions later.
For n strings of 20 characters:
char** a;
int main()
{
int n;
do
{
cout << "N= ";
cin >> n;
}
while(n < 1);
a = new char*[n];
for(int i = 0; i < n; ++i)
{
a[i] = new char[20];
}
for(int i = 0; i < n; ++i)
{
memset(a[i], 0, 20);
}
return 0;
}