For loop length problems - c++

The code is to input strings at run time but the code is accepting string one less than the mentioned sized n? Where is the error?
suppose n=3,but the loop is running only twice i.e. n-1 times thus taking only two strings as input
int main(){
int n;
cin>>n;
char str[n][100];
for(int i=0;i<n;i++)
{
char c;
int j=0;
while((c=getchar())!='\n')
{
str[i][j++] = c;
}
str[i][j] ='\0';
}
}

It is reading the \n return character (from when you filled n) and making the first string empty. Just do another getchar() before the first test for end of input to get rid of it.
For robustness, you could also try: cin.ignore(INT_MAX);cin.clear();cin.sync();.
Example (My compiler doesn't like part of your syntax so I had to redo it, focus on the new getchar:
int main() {
int n;
cin >> n;
char** str = new char*[n];
for (int i = 0; i < n; i++)
str[i] = new char[100];
getchar();
for (int i = 0; i<n; i++)
{
char c;
int j = 0;
while ((c = getchar()) != '\n')
{
str[i][j++] = c;
}
str[i][j] = '\0';
}
for (int i = 0; i < n; i++)
delete[] str[i];
delete[] str;
}
(Yes I know I'm 1 star away from http://wiki.c2.com/?ThreeStarProgrammer, just doing this to answer the question.)

Related

Why the output is not showing?

My program is to find the smallest positive number missing from an array. With the following input I expect an output of 2.
6
0
-9
1
3
-4
5
My problem is that it does not give any output. Can anyone explain this please?
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin >> n;
int array[n];
for (int i = 0; i < n; i++)
{
cin >> array[n];
}
int const N = 1e4+2;
bool indexarray[N];
for (int i = 0; i < N; i++)
{
indexarray[i] = false;
}
for (int i = 0; i < n; i++)
{
if (array[i] > 0)
{
indexarray[array[i]] = true;
}
}
int ans = -1;
for (int i = 1; i < N; i++)
{
if (indexarray[i] == false)
{
ans = i;
}
}
cout << ans << endl;
return 0;
}
I think because int array[n]; makes an array called array with n elements in it, with the first one starting at array[0].
cin >> array[n]; needs to modify array[n], but because the first element is array[0], the last element is array[n-1], and array[n] does not exist. Your code gave an error and exited.
Try changing
for (int i = 0; i < n; i++)
{
cin >> array[n];
}
to
for (int i = 0; i < n; i++)
{
cin >> array[i];
}
Also, I think variable length arrays are non-standard, so maybe try changing that. Replace it with std::vector<int> array(n) should work.

C++ replacing values in a dynamic 2D Array

I'm trying to replace the '.' in my array with 'O'but it inserts it in between rather than taking its place. Please help I don't know what I'm doing wrong.
#include <iostream>
using namespace std;
char** createField(int w, int l)
{
int obstacles;
char ** arr = new char * [w];
for(int i=0; i<w; i++)
{
arr[i] = new char[l];
}
//Initializing the values
for(int i = 0; i < w; ++i)
{
for(int j = 0; j < l; ++j)
{
arr[i][j] = 0;
}
}
cout<<"Enter number of obstacles: ";
cin>>obstacles;
int x=0;
int y=0;
for (int j = 0; j < obstacles; ++j) {
cout<<"Enter location of obstacles: ";
cin>>x>>y;
arr[x][y] ='O';
}
for(int i = 0; i < w; ++i)
{
for(int j = 0; j < l; ++j)
{
if(i==0 || i == w-1){
cout<< arr[i][j]<< 'W';
}else if(j==0 || j==l-1){
cout<< arr[i][j]<< 'W';
} else
cout<< arr[i][j]<< '.';
}
cout<<"\n";
}
return arr;
}
int main() {
int w;
int l;
cout << "Enter the Width: ";
cin >> w;
cout << "Enter the length: ";
cin >> l;
//Pointer returned is stores in p
char **p = createField(w, l);
//Do not Forget to delete the memory allocated.It can cause a memory leak.
for (int del = 0; del < w; del++) {
delete[] p[del];
}
delete[]p;
}
Here is an example of my output, I want the 'O' to replace the '.' rather than be in between the two. Also if someone could explain why this is happening that would be really helpful Thanks.
Example of output: w.O.w
Desired output: w.Ow
When you set arr[i][j] = 0, it will cast 0 into char before assigning it to arr[i][j]. 0 casts to the literal '\0' which means a null character. Later when you print the contents of arr, the null characters cannot be seen in output which is part of the underlying cause of your confusion. Hope that explains what's going on a little bit better.

How to not get end of line character using cin.get() in c++

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;
}

Scanning char array and putting it in struct properly in c++

Wanted to get my char array to be in a struct, but it crashes.
As I realised after, there is also a problem when scanning the array.
The input string consists of two words, name and surname, separated by a space. I haven't yet written the part where it scans the second word, so now it scans only the first.
The check lines in code have s weird output. I input "James" and it gives me "J8224a8224m8224e8224s8224" and then crashes.
#include <iostream>
#include<string.h>
using namespace std;
struct base
{
char* name;
char* surname;
int point1;
int point2;
};
main()
{
setlocale(LC_ALL, "rus");
int n;
cin >> n;
base a[n];
char symb;
char sym[20];
int j = 0;
for (int i = 0; i < n; i++)
{
do
{
symb = getchar();
sym[j] = symb;
j++;
} while (symb != ' ');
for (int k = 0; k < j; k++) //check
cout << sym[k] << ' '; //check
strcpy(sym, a[i].name);
j = 0;
}
}
There are several errors:
You cannot use static initialization for base a[n], because variable n is not known while compiling.
You have to initialize a[i].name before you do strcpy.
You shlould use sptncpy instead of strcpy if you know lenght which is j.
You code should look like this
int main()
{
setlocale(LC_ALL, "rus");
int n;
cin >> n;
base *a = new base[n];
char symb;
char sym[20];
int j = 0;
for (int i = 0; i<n; i++)
{
do
{
symb = getchar();
sym[j] = symb;
j++;
} while (symb != ' ');
for (int k = 0; k<j; k++) //check
cout << sym[k] << ' '; //check
a[i].name = new char[j];
strncpy(sym, a[i].name, j);
j = 0;
}
}

User defined matrix of chars

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;
}