Error in inputting a 2d character array - c++

I am entering a 2D character array and have to stop entering when the user hit the enter key . But my code is not showing any output.
Input:
5 // where this is the number of columns,
// number of rows are unknown so have taken maximum rows as: 40
array:
toioynnkpheleaigshareconhtomesnlewx
Expected output:
i = 7, j = 5
Here is my code:
int main(){
char a[100][100];
int n, i, j, p, q;
cin >> n;
if(n==0)
exit(0);
for(i = 0; i < 40; i++){
for(j = 0; j < n; j++){
cin >> a[i][j];
if(a[i][j]==13) // 13 = ASCII code for enter key
goto jump;
}
}
jump:
cout<<i<<"\n"<<j<<"\n";
}
But it is not printing anything.
What could be wrong with it?

This is happening because cin ignores white space and newline ('\n', whose ASCII code is 13). This means the condition if(a[i][j] == 13) never evaluates to true.
Solution: Use cin.get(a[i][j]) instead of cin>>a[i][j]
This works because the cin.get() method does not ignore the newline character ('\n').

Related

C++ Program to print sum of digits

//Program to print sum of digits
#include <iostream>
using namespace std;
int main()
{
int n, m, sum = 0;
cin >> n;
for(int i = 0; i < n; i++)
{
m = n % 10;
sum += m;
n = n / 10;
}
cout << sum;
}
//Outputs
// Input = 123
// Output = 5 (should be 6)
// Input = 0235
// Ouput = 8 (should be 9)
Not printing the right answer when input no. is starting from 1 or 0.
By using While (n>0), it's giving the right output but I can't figure out why?
For starters the user can enter a negative number because the type of the variable n is the signed type int.
Thus neither loop either
for(int i = 0; i < n; i++)
or
while (n>0)
will be correct.
A correct loop can look like
while ( n != 0 )
And you need to convert each obtained digit to a non-negative value or you should use an unsigned integer type for the variable n.
As for this loop
for(int i = 0; i < n; i++)
then it entirely does not make a sense.
For example let's assume that n is initially equal to 123,
In this case the in the first iteration of the loop the condition of the loop will look like
0 < 123
In the second iteration of the loop it will look like
1 < 12
And in the third iteration of the loop it will look like
2 < 1
That means that the third iteration of the loop will not be executed.
Thus as soon as the last digit of a number is less than or equal to the current value of the index i the loop stops its iterations and and the digit will not be processed.

Convert number in binary and print out as matrix (C++)

Before you read ahead or try to help, this question is regarding my homework so the requirements to this question will be very specific.
I am writing a code that takes a user input between 0 and 511 and converts it into a binary number. Then the program will replace all the 1's in the binary number with T and all the 0's in the number as H. Afterwards it will print out the results (the binary number with the H and T replacement) as a 3*3 matrix.
This is the desired output (not what I have but what I want):
Enter a number between 0 and 511: 299
The binary number is: 100101011
The matrix is:
THH
THT
HTT
The problem with my code is that I am unsure of how to replace an array that consists of all integers to have certain parts of the index to be either characters or strings. For sure the part with the binary number conversion works but the replacement of the 0's and 1's of the array is where the trouble is at. I am also unsure of how to print out the matrix result. I assume it goes either of 2 ways: 1. The program creates a new array for the previous array's elements stored and prints out the matrix array instead. 2. There is a way to only print the array 3 lines at a time. The only way I can think of is to somehow cut the for loop short and add a line break after every 3 values. I am aware that there are a few pointable errors in my code but I do not know how to fix them.
Although this is in the C++ language, what I have learned is the C style syntax (no std:: kinds of code or stuff like that because I haven't learned it yet and I will not understand it) So far I have learned basic arrays, loops, and functions.
#include <iostream>
using namespace std;
int main(){
int arr[10];
int input, i;
cout<<"Enter a number between 0 and 511: ";
cin>> input;
for(i = 0; input > 0; i++){
arr[i] = (input % 2);
input = input / 2;
}
cout<<"The binary number is: ";
for(i = i - 1; i >= 0; i--){
cout<<arr[i];
}
string newArr[10] = arr[10]; //the error here states that the array initializer must be an initializer list
for(int i = 0; i < sizeof(arr)/sizeof(arr[10]); i++){
if(arr[i] == 1){
arr[i] = "T"; //the error here mentions that a string/ character cannot be assigned with a integer array
}
else{
arr[i] = "H";
}
}
for(int i = 0; i < sizeof(arr)/sizeof(arr[10]); i++){
cout<<arr[i]<< " ";
}
}
This would be sufficient:
#include <iostream>
using namespace std;
int main()
{
// you never actually checked if the input is valid
// so you may or may not want this loop:
int input;
do
{
cout << "Enter a number between 0 and 511: ";
cin >> input;
} while ((input < 0) || (input > 511));
// space for matrix, new lines and null
// to construct a null terminated string
char buffer[3 * (3 + 1) + 1];
int i = 0;
// since the bits are read from left to right
// I will use a mask instead of bit shifting the input
int bit = 1 << 9;// 2^9 == 512
for (int r = 0; r < 3; r++)// rows
{
for (int c = 0; c < 3; c++)// columns
{
// this could come after the check
// and then bit would start at 256
bit >>= 1;
// perform the check and add the corresponding letter
buffer[i++] = (bit & input) ? 'T' : 'H';
}
// add new lines
buffer[i++] = '\n';
}
// if you don't want the last '\n'
// this could be { buffer[--i] = '\0'; }
buffer[i++] = '\0';
cout << buffer;
}

How to print the string that has lowest ascii sum out of other possibilities

I am writing a program that creates string of length n with x distinct values however it's required that the string created should have lowest ascii sum , my code creates n length string with x distinct values but it doesn't create lowest ascii valued string, help is required what am i doing wrong
int main()
int n,x;
int p= 97;
cin>>n;
cin>>x;
if (n<x || x==1){
cout<< "00";
}
else {
for(int j = 0; j<n ; j++)
{
char ans = (char)(p+(j%x));
cout << ans;
}
}
return 0;
}
If you need to have x distinct characters but need the lowest ASCII value string, you need to make a simple observation: greedily insert as many 'a' as you can (n-x+1, to be precise). Since you need x-1 distinct characters other than 'a', proceed to insert 'b', 'c' and so on, in sequential order.
how about this?
char ans = (char)(p + (j % 26));

Find the numbers with exactly 2 nines in them

We input n numbers and the program must type the ones that have exactly 2 ‘9’ in them. (for instance, if we input 9193 then the program will type it, but if we write 73999 or 256 it will not give any output).
So I wrote this code
int main(){
int a, n, i, count=0, y;
cin>>n;
for(i=1; i<=n; i++){
cin>>a; y=a;
while(y>0){
if(y%10==9) count++;
y=y/10;
}
if(count==2) cout<<a<<endl;
}
return 0;
}
But I cannot understand why this does not work.
If I change it and write this way it works.
int main(){
int a, n, i, count, y;
cin>>n;
for(i=1; i<=n; i++){
count=0;
cin>>a; y=a;
while(y>0){
if(y%10==9) count++;
y=y/10;
}
if(count==2) cout<<a<<endl;
}
return 0;
}
Will much appreciate if you explain this to me.
Just read as string (or convert it to) and count:
for(i=1; i<=n; i++){
std::string numstr;
std::cin >> numstr;
if( std::count( numstr.begin(), numstr.end(), '9' ) == 2 )
std::cout << numstr << std::endl;
}
If you don't reset count to 0 each time through the main loop, you're adding the count in the new number to the count from the previous number.
So if you type 19 for the first number, you'll set count to 1. Then if you type 939 for the second number, it will set count to 3, and the test if (count == 2) will not succeed, even though there were 2 nines in that number. After this, count will never become 2, because you'll keep adding to it.
You need to start counting from the beginning for each number.
Note that your algorithm won't work for negative numbers. -9 % 10 is -9, not 9.
We need to initialise count=0 for every case.

Appending vectors. Result won't print

I'm trying to enter integers for a and b and then print those integers put together. For example, entering 1 2 3 4 for a and 4 3 2 1 for b would yield: 1 2 3 4 4 3 2 1. I don't understand why my program isn't printing this. Whenever I enter -1, nothing happens. Am I doing the process wrong while the program is running? Help is appreciated.
#include <iostream>
#include <vector>
using namespace std;
vector<int> append(vector<int> a, vector<int> b)
{
int n = a.size();
int m = b.size();
vector<int> c(n + m);
int i;
for (i = 0; i < n; i++)
c[i] = a[i];
for (i = 0; i < m; i++)
c[n + i] = b[i];
return c;
}
main()
{
vector<int>a, b, c;
int temp;
cin >> temp;
while (temp != -1) {
a.push_back(temp);
cin >> temp;
}
cin >> temp;
while (!cin.eof()) {
b.push_back(temp);
cin >> temp;
}
c = append(a, b);
for (int i = 0; i < c.size(); i++)
cout << c[i] << " ";
cout << endl;
}
You have two loops, one to input the vector a and another to input b.
Hitting -1 once would terminate only the first loop. The second one is terminated by an eof which you still haven't entered. So either enter an eof (specific to your system) or have the second loop terminate at -1 (in which case you'll need to enter -1 once more).
You say
Whenever I enter -1, nothing happens.
That's because you reach the second cin >> temp statement at that time (just before while.eof() loop). That's when you start inputting values for b vector. You end that loop by entering EOF character in the stream (CTRL+Z on windows, CTRL+D on linux).