c++ Replacing character with a number [closed] - c++

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have this code. What i wanted to do is to replace every letter from every char with indicated number. Like for A is 10, and so on until J, 19. My code works well if i have only one letter in my char array, but if i have more after another it copies useless things. I think that something is wrong with strncat.
#include<conio.h>
#include <cstring>
#include <iostream>
using namespace std;
int main()
{
char litera[11]={"ABCDEFGHIJ"};
char cifra[11]={"0123456789"};
char rezultat[256]={0};
int n;cin>>n;cin.get();
for(int i=0;i<n;i++)
{
char x[256];
cin.get(x,256);cin.get();
int k=strlen(x);
for(int j=0;j<k;j++)
{
int p = strchr(litera,x[j])-litera;
if(p>=0 )
{
strncat(rezultat, x,j);
// my p is the indicator for letter and number
strcat(rezultat,"1");
// I'm copying an 1 there because i have numbers
// between 10-19 and in my int array i have only
// the second cipher
strcpy(x,x+j);
rezultat[strlen(rezultat)]=cifra[p];
}
}
cout<<rezultat<<endl;
memset(rezultat,0,sizeof(rezultat));
}
getch();
return 0;
}
Input: 07B, 1AA, C8A
Output: 0711, 11010, 12810
My output:
0711
110AA1
12C810
If you guys can tell me where the problem is, you'll help me a lot, every suggestion is well received, even if is not about this problem. Thanks!

If it is allowed to use vector and string then you can try the following (I tested it and it works.) The input here should be line by line(each line is a new string to be converted) but of course you may modify this part based on your input format:
Include those:
#include <vector>
#include <iostream>
#include <string>
//#include <conio.h>
//#include <cstring>
//using namespace std;
int main()
{
int n;
std::cin >> n;
while (n--)
{
string input;
std::cin >> input;
vector<char> resultat;
for (int i = 0; i < input.size(); i++)
{
if (input.at(i) >= 'A' && input.at(i) <= 'J') // it is a letter between A and J
{
int number = input.at(i) - 'A' + 10;
char ones = (char)(((int)'0') + (number % 10));
char tens = (char)(((int)'0') + (number / 10));
resultat.push_back(tens);
resultat.push_back(ones);
}
else
resultat.push_back(input.at(i));
}
for (int i = 0; i < resultat.size(); i++)
{
std::cout << resultat[i];
}
std::cout << endl;
}
}
if string is not allowed just use your character array. There seems to be nothing wrong in your input format.
If vector is not allowed either, then you may create a char pointer the initialize it based on the final size.
For example:
int newSize=0;
for (int i = 0; i < input.size(); i++)
{
if (input.at(i) >= 'A' && input.at(i) <= 'J')
newSize+=2;
else
newSize++;
}
char* resultat = new char[newSize];
...
Then just fill the resultat.
Hope that helps!

Do you have to do it with your multiple arrays? You could perform a switch-case for only specified inputs. Since you are replacing letters A-J with numbers 10-19, you can easily implement this in switch case. You can also check for incorrect input as well.
If you have to use arrays, first question is why is you numerical array the single digits? Is this is constraint? Cant you use :
char cifra[11]={"10","11","12","13","14","15","16","17","18","19"};
for the array instead, that way you can refer to the array index and replace it using the index? This way, you can compliment the arrays by just using index referencing to replace the output based on the index, such as A is index 1 for alphabetical array which refers to index 1 of the numerical array which is "10" so you just print the array index value to a variable and output it.

Related

Reversing string using stack (static array) in c++

i am new to this concept in c++
i am trying to reverse string using stack static array implementation in c++.
Input: qwerty
expected output: ytrewq
output which i am getting is: trewq
Can some one explain me why is this happening and any possible solution.
Here's my code
#include <iostream>
#include <string>
using namespace std;
#define SIZE 10
string arr[SIZE];
unsigned a = -1;
void push(char ch) {
a = a + 1;
arr[a] = ch;
}
void pop() {
a = a - 1;
}
void display() {
for (int j = a; j >= 0; j--)
cout << arr[j];
}
int main() {
string str;
getline(cin, str);
for (int i = 0; i < (str.length() - 1); i++)
push(str[i]);
display();
}
Remove the "-1" in :
for(int i=0;i<(str.length())-1;i++)
Else your array doesn't contains the last character.
I made the test without the -1, it works well.
The condition "< str.length()" is enough to loop on all string caracter.
In similar case, use the debugger to see what contains your variable. In these case the variable "arr" don't contains the last input caracter.
You push everything on the stack, so the last element can be popped first. Then do popping to fill a reversed strng. The stack should be a char array.
As this is typically a task, the rest is your puzzle.
Pop typically gives you the top element as:
char pop() {
char ch = arr[a];
--a;
return ch;
}
The correct way to reverse a string would be to do:
std::reverse(str.begin(), str.end());
But I think this might be homework/study so look at your output. You are just missing the last letter. That suggests the upper limit of your loop is wrong doesn't it?

sorting in c++ giving me a blank output

Hi I'm trying to make a program that takes a sum as an input lets say 1+2+3+2+2+1 and must sort the sum out as 1+1+2+2+2+3
this is the code
#include <iostream>
#include <algorithm>
#include <string.h>
using namespace std;
int main() {
string s;
char w[100];
char x[100];
cin>>s;
//moving string s to array w to remove the '+' charachter for sorting
for (int i=0; i>s.size() ;i++){
if (s.at(i) = '+')continue;
else s.at(i) == w[i];
}
//sorting array w
sort(w,w+100);
//moving array w to array x and re-adding the '+' after sorting
for (int y=0; y > s.size();y++){
w[y]==x[y];
x[y+1]=='+';
}
cout<<x;
return 0;
}
but when i run it, it gives me a blank output
this is my first time at a c++ program im still a beginner at it
thanks for the help in advance!
I can see that you are new to the language, as you lack some understanding of basic concepts. I will first give you some tips and explanation on your mistakes, then I'll give you a more suitable solution.
First of all, try avoiding using C-styled arrays like you do with w and x. They are prone to errors because of no bounds checking, look into using std::vector or std::array instead.
== and = are NOT the same! == is used when comparing two things and = is used for assigning the right side to the left side.
Your loops are completely wrong, using
for (int i=0; i>s.size() ;i++)
will never even enter the loop. Use i < s.size() of course. I also recommend using ++i instead of i++ but that is not too important.
Your "thinking in code" is sometimes weird too
for (int i=0; i>s.size() ;i++){
if (s.at(i) = '+')continue;
else s.at(i) == w[i];
}
(not minding the > and = mistakes), why not check if it is not '+' instead of continueing and then doing something?
this code should logically be
for (int i=0; i>s.size() ;i++){
if (s.at(i) != '+') s.at(i) == w[i];
}
Last but not least, try to be consistent. First you use i as loop variable and the second time you use y. Not that it matters, but consistency is always good when coding.
I made a quick solution for your problem:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
string input;
cin >> input;
vector<int> nrs = vector<int>(); //initialising this is not really needed
for (char c : input) //range based for loop, prevents mistakes with indices
{
if (c != '+')
{
nrs.push_back(c - '0'); // a char minus '0' gives the numerical value
}
}
sort(nrs.begin(), nrs.end());
string answer;
for (int nr : nrs) //range based for loop again
{
answer += to_string(nr); //use to_string to convert an int to a string
if (nr != nrs.back()) //to avoid adding the '+' after the last character
{
answer += '+';
}
}
cout << answer << endl;
return 0;
}

Why is my C++ program not working? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am trying to build a program that reads numbers from "bac.txt" and returns the 2 digit number/numbers (10,11,12,...,99) that appear most frequently. For example if the file "bac.txt" contains 393 17775787 72194942 12121774 it will return 77 and 21. I have managed to build a working function counter(int n) that can count how many times n is found in the file and returns i which is the number of times n has been found. Now I can't seem to find a way to print to the screen the number/numbers that are found most often. I tried to use some kind of for loop but it doesn't work.
Here is my code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int counter(int n){
int i=0,j=0;
char x1=n/10+'0';
char x2=n%10+'0';
char a;
char b=NULL;
fstream fisier("bac.txt", fstream::in);
while (fisier >> noskipws >> a) {
if(b==x1&&a==x2)
i++;
b=a;
}
return i;
}
int main()
{
int v[90];
int v1[90];
int i,maxim=0,nr;
for(i=10;i<100;i++)
{
v[i]=counter(i);
if(v[i]>maxim)maxim=v[i];
}
for(i=10;i<100;i++)
if(v[i]==maxim)
cout<<i;
}
I have corrected the code.It works now.
You may check the changes.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int counter(int n)
{
int i = 0, j = 0;
char x1 = n / 10 + '0';
char x2 = n % 10 + '0';
char a;
char b;
fstream fisier("bac.txt", fstream::in);
fisier >> b;
while (fisier >> a) {
if (b == x1 && a == x2)
i++;
b = a;
}
return i;
}
int main()
{
int v[101];
int i, maxim = 0, nr;
for (i = 10; i < 100; i++) {
v[i] = counter(i);
if (v[i] > maxim)
maxim = v[i];
}
for (i = 10; i < 100; i++)
if (v[i] == maxim)
cout << i;
}
i can't say you why your program's not working, but i can say you how i'd solve it. you have to store in an int vector the 2 digit number that you read from file (ex. if file contains 1234 the int vector will contains 12 23 34) than you have to find the 2 number that appear most times, so, you have read the first vector element and store it in a variable, than you count how many times it appear in the vector and you save the number you were searching in max_a and the times it appear in max_times_a (remember that when you find in the vector the number you're searching you have to put a -1 on it) than you search in the vector another number and count how many times it appear (putting -1 on that number) than you store that number in max_b and the times it appears in max_times_b. than what you have to do is to slide the vector and if you reach the end becouse you only read -1 you have max_a and max_b as result, but if you find a number you have to count how many times it appear and checking if it appear most times of max_a or max_b, and in case it appear most times you have to swap the values. i hope to have been useful to you.
Tommaso

how can we do n nested for loops where n is dynamic [duplicate]

This question already has answers here:
c++ : dynamic number of nested for loops (without recursion)
(3 answers)
Closed 6 years ago.
I have read the following questions but have not found a solution to my problem:
c++ : dynamic number of nested for loops (without recursion)
variable nested for loops
actual problem statement is :-
Job and Jimmy both are playing with numbers. Job gives Jimmy an array of numbers and asks him to tell the minimum possible last number of a non decreasing sequence of length L.
Input Format
First input line consists of a number which is size of array N.
Next line contains N space separated elements of array.
Next line contains length of the non decreasing sequence i.e. L.
Output Format
You have to print the minimum possible last number of a sequence and if their is no non-decreasing sequence of length L, then print -1
Sample Input
7
9 7 2 5 4 11 12
3
Sample Output
11
Explanation
In sample input, possible non-decreasing sequences of length L=3 are (9,11,12) , (7,11,12) , (2,5,11) , (2,4,11) , (2,5,12) , (2,4,12) , (2,11,12) , (5,11,12) , (4,11,12) and the minimum last number is 11 for the sequences (2,5,11) and (2,4,11). Hence, the answer is 11."
my code...
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int fact(int y,int x)
{
static int temp=0;
if(temp==x)
{
temp=0;
return 1;
}
else
{
++temp;
return y*fact((y-1),x);
}
}
int main() {
int num,randmax,n,s,q,w last=-1, minlast=-1;
cin>>n;
vector<int> a(n);
for(int i=0;i<n; i++)
{
cin>>a[i];
}
cin>>s;
vector<vector<int>> c;
q=fact(s);
c.resize(q);
for(int i = 0 ; i < q ; ++i)
{
//Grow Columns by n
a[i].resize(s);
}
w=q;
randmax=n-1;
int k=0;
while(w)
{
for(int i=0 ; i<n ; i++){
}
num=rand()%randmax; // this works perfect as expected
c[][i]=a[num];
}
w--;
}
/*for(int i=0;i<n;i++)
{
for(int j=i+1;j<n;j++)
{
for(int k=j+1;k<n; k++)
{
if((a[i]<=a[j])&&(a[j]<=a[k]))
{
last=a[k];
if(minlast=-1)
{
minlast=a[k];
}
if(last<minlast){
minlast=last;
}
}
}
}
}
*/
cout<<last;
return 0;
}
`
I would tell you what I tried to do... I thought of mapping the data by having them randomly assigned in one of my array and then computing them..
I got lost somewhere in my code...plz gimme an solution to it...and more imp. a good explanation of the same as I got stuck at times when I need a dynamic nested n loop type of thing...
also it would be more helpful if you edit in my code or algo so that I could learn where my mistakes are there...
Thanks in advance for you time...
As the answers your links have pointed out, you can imitate a dynamic amount of for loops by using an array David gives a fine implementation here.
For the actual problem you gave though, I see no need for a dynamic amount of for loops at all. The problem is a standard non-decreasing subsequence problem with a slight variation.
#include <iostream>
#include <fstream>
int N, L;
int arr[100], seq[100];
int bst;
int main() {
std::ifstream file ("c.txt");
file >> N;
for(int n = 0; n < N; ++n)
file >> arr[n];
file >> L;
file.close();
bst = 1e9;
for(int i = 0; i <= N; ++i) seq[i] = 1e9;
for(int i = 0; i < N; ++i)
{
int x = 0;
while(seq[x] < arr[i]) ++x;
seq[x] = arr[i];
if(x + 1 >= L)
bst = std::min(bst, arr[i]);
}
std::cout << bst << std::endl;
return 0;
}
This code should solve your problem. The first part does standard parsing and initialization. The rest is a variation on the LIS problem, which has several standard algorithms that solve it. Here, we just check that whenever we extend an array of length L or longer, we see if the element is smaller than our current.

c/c++ scanf/cin reads int from multiple lines

I'm doing some basic input parsing in c/c++.
format: number of values, followed by space separated values:
3
5 2 4
The problem here is the lack of a space after the first line. This causes cin and scanf to read 35 into the first variable, instead of 3.
int num;
scanf("%d", &num);
int array[num];
for (int i = 1; i <= num; i++) {
scanf("%d", &array[i]);
}
How do I get cin, or scanf, to stop parsing at a newline?
Edit:
Is it bad not to init variables even if they are written to later, before being read? (int num)
It works if I type the input in, but not if I paste it. Any clue?
std::cin interprets newline characters as spaces so there is the possibility the file you are working with contains something other than a newline. You are also using a non-standard extension to declare the array. This is not portable and not guaranteed to be supported by all compilers. I suggest you switch to using std::vector instead.
Your for loop is also incorrect. Array's used zero based indexing to access their elements. Because of this you end up accessing the array out of bounds which is undefined behavior. This means your program might crash, it may overwrite other variables or you might not notice any symptoms at all. This may also cause the symptom you are experiencing if it overwrites other variables.
The example below uses C++ input streams instead of scanf to provide better error checking.
#include <istream>
#include <vector>
std::vector<int> load(std::istream& in)
{
std::size_t count;
std::vector<int> data;
// If the user does not enter a number "in >> count" will fail.
if (in >> count)
{
int value;
while (count-- && in >> value)
data.push_back(value);
}
return data;
}
#include <iostream>
int main()
{
auto data = load(std::cin);
for (auto i : data)
std::cout << i << std::endl;
}
You can test this without reading from a file by using std::stringstream as the input.
#include <iostream>
#include <sstream>
int main()
{
std::stringstream text("3\n5 2 4");
auto data = load(text);
for (auto i : data)
std::cout << i << std::endl;
}
Within the for loop you started the array at position 1 and not 0. Which would cause going out of bounds, as you wanted to write to element 2 of the array. If you allocate an array of 2 elements the valid elements are going to be 0 and 1. This code works:
int num;
scanf("%d", &num);
int array[num];
for (int i = 0; i < num; i++)
{
scanf( "%d", &array[i] );
}
Start array from 0 as array indexes start from 0 - like:
for (int i = 0; i < num; i++)
You are starting first element from 1 that makes it undefined. Moreover, you should make dynamic array.
I liked Lidong Guo's code, and have modified it to run with Microsoft's C Compiler.
The only change was to move all of the data definitions ahead of any executable code, plus I added a space between the printed numbers.
#include <stdio.h>
#include <stdlib.h>
main()
{
int num;
int *array; //[num];
int i;
scanf("%d\n", &num);//here deal with the newlinw
array= malloc(sizeof(int) *num);//[num];
for (i = 0; i < num; i++)
{//the loop .start 0 end num -1
scanf("%d", &array[i]);
}
for (i = 0; i < num; i++)
{
printf("%d ", array[i]);
}
free(array);
}
[Edit: The Answere is specific to C++, as the Question also have a C++ tag]
Well first thing first.
You array defination is wrong .
int array[num]; // Super wrong way
You are not supposed to pass a variable as index while defining an array, its not allowed. Else, it will cause "nasal demon".
int * array = new int[num] //correct way
The code might be working correctly now but the array definition given by you lies under the category of UB.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num;
scanf("%d", &num);
int *array= malloc(sizeof(int) *num); // num is known at runtime
int i;
for (i = 0; i < num; i++) { //starts at 0, ends at num - 1
scanf("%d", &array[i]);
}
for (i = 0;i< num; i++) {
printf("%d", array[i]);
}
free(array);
}
Change the
scanf
statement to
scanf("%d", &array[i]);
Also array indexing starts from 0 and ends at num-1
Start your loop from 0 and end it at num-1,i.e
for (int i = 0; i < num - 1; i++)
scanf("%d", &array[i]);
And the reason for pasted input does not work is that it doesn't contain newline between two lines