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;
}
Related
To find all sequences of fixed length which contain only 0 and 1 I use this code:
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
void print_array(vector<string> arr) {
cout << '[';
int n = arr.size();
for (size_t i = 0; i < n; i++) {
cout << arr[i];
if (i < (n - 1)) {
cout << ", ";
}
}
cout << ']' << endl;
}
vector<string> get_variants(int n) {
vector<string> result = {"0", "1"};
vector<string> temp;
temp.reserve(2);
result.reserve(2);
for (int i=0; i < (n - 1); ++i) {
copy(result.begin(), result.end(), temp.end()); // [1]
for (int j=0; j < result.size(); ++j) {
temp[j] += "0";
result[j] += "1";
}
copy(temp.begin(),temp.end(), result.end());
temp.clear();
}
return result;
}
int main(int argc, char const *argv[]) {
int n;
cin >> n;
vector<string> maybe = get_variants(n);
print_array(maybe);
return 0;
}
But vector temp is empty, before copying in line which I marked [1] and after. So, my program's output was [0111, 1111]. What I'm doing wrong?
A more straightforward way than using std::copy is the use of .insert():
temp.insert(temp.end(), result.begin(), result.end()); //1
...
result.insert(result.end(), temp.begin(), temp.end()); // 2nd copy
You are writing to temp.end() and result.end(). These iterators represent "one past the end", and therefore writing to these iterators is Undefined Behavior.
You seem to be looking for std::back_inserter. This will create an iterator that will insert a new element to your container when it is written through.
std::copy(result.begin(), result.end(), std::back_inserter(temp));
While this answers the posted question, there remain other errors in your code leading to Undefined Behavior.
Trying to compile your program with a C++ compiler will not work, because you include #include <bits/stdc++.h>which is a non tC++ standard compliant header.
You should never include this file.
You are using typical competitive programming stuff, but including all C++ headers and not use them will eat up Compile time for no good reason.
Then, you typedef the typical competitive programming abbreviations. 2 of them, you do not use. Then there is no reason to define them.
I recommend to not do this any longer. And in C++, please use the using statement.
Then, although you want to be fast, you pass arr by value to your print function. This will copy the whole vector.
You assign/compare a lot of int with unsigned int values. This you should not do.
Additionally: Please use meaningful variable names and write comments. The more the better.
Regarding your specific bug. Both std::copy statements use end iterator as target. End is end. It is past the end of the vector. Please use std::back_inserter instead.
Regarding the algorithm. I took a while for me to realize that you basically want to create binary numbers. Nothing else. Unfortunately you translated that in a very complicated way.
Normally, you just would count from 0 to 2^n-1 and then show the data. Thats all. Becuase the numbers may be of arbitraty length, we will use manual addition of digits like in scholl on a peice of paper. Very simple.
Everthing then biols down to some lines of code.
Please see:
#include <iostream>
#include <vector>
int main() {
// Read length of binary number to create and validate input
if (int numberOfDigits{}; (std::cin >> numberOfDigits and numberOfDigits > 0)) {
// Here we will store the binary digits, so 0s or 1s
std::vector<int> digits(numberOfDigits,0);
// Som printing helper
std::cout << '[';
bool printComma{};
// We need to print 2^n possible combinations
for (int i = 0; i < (1 << numberOfDigits); ++i) {
// Print comma, if need
if (printComma) std::cout << ','; printComma = true;
// Print all digits of the binary number
for (const int d : digits) std::cout << d;
// Calculate next binary number
int carry = 0;
for (int index=numberOfDigits -1; index >=0; --index) {
const int sum = digits[index] + ((index == (numberOfDigits - 1)?1:0)) + carry;
carry = sum / 2;
digits[index] = sum % 2;
}
}
std::cout << ']';
}
}
If there should be questions, then I am happy to answer.
The purpose of this code is to insert an x in between repeating letters. For example, if I were to input "CoolBoolFallmoose", the output would be "CoxolBoxolFalxlmoxose".
The code is also supposed to make an even number of pairs of letters, so if there is an odd amount of characters, an x is added to the end of the string. An example for this would be if we had "ball", it would become "balxlx" to make even pairs: "ba" "lx" "lx".
This is the code I have so far:
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main(){
string cipher, plain, paired = "";
cout << "input plaintext(no spaces, lowercase):\n";
cin >> plain;
for (int i=0;i<plain.length();i++){
if (plain[i]==plain[i+1]){
plain.insert(i,'x');
}
paired[i]=paired[i];
cout<<paired[i];
}
if (paired.length() % 2!= 0){
paired=+'x';
}
cout<<paired<<endl;
return 0;
}
The output I get is just the same as my input, no "x" added in any place.
The issue I am having is, every time I try to use the append() or insert() function for strings, I get an error from my compiler, which is xCode. Is there another way to solve this code?
EDIT: The error says:
No matching member function to call for insert
It also comes up for append().
I don't really know what you wanted to do with this part:
paired[i]=paired[i];
cout<<paired[i];
but otherwise the logic is good. Here is my take on it, x is a counter:
#include <iostream>
#include <string>
using namespace std;
int main(){
string m,n;
int x = 0;
cout << "Input: " << endl;
getline(cin, m);
for(int i = 0;i < m.length();i++){
x++;
n = n + m[i];
if(m[i] == m[i+1]){
n = n + 'x';
x++;
}
}
if((x % 2) != 0){
n = n + 'x';
}
cout << n;
return 0;
}
If you look at the available overloads of std::string::insert(), you will see that your statement plain.insert(i,'x'); does not match any of them, hence the compiler error. The overloads that takes a single char require either:
an index and a count (you are omitting the count)
an iterator and an optional count
There is, however, a couple of overloads that take just an index and a value, but they require a const char* or a std::string, not a single char.
Also, paired[i]=paired[i]; is a no-op. Except in your case, since paired has a size() of 0 since you never append anything to paired, so actually any access to paired[...] is undefined behavior.
Try this instead:
#include <iostream>
#include <string>
using namespace std;
int main(){
string plain, paired;
cout << "input plaintext(no spaces, lowercase):\n";
cin >> plain;
paired = plain;
for (string::size_type i = 1; i < paired.size(); ++i){
if (paired[i] == paired[i-1]){
paired.insert(i, 1, 'x');
// or: paired.insert(paired.begin()+i, 'x');
// or: paired.insert(i, "x");
// or: paired.insert(i, string{'x'});
// or: paired.insert(paired.begin()+i, {'x'});
++i; // skip the x just inserted
}
}
if (paired.size() % 2 != 0){
paired += 'x';
}
cout << paired << endl;
return 0;
}
Demo
A couple of points
First, Although the string.insert function says it takes an int as its first argument it really wants an iterator in this case.
Second, you are inserting elements into your "plain" string which increases its length and you have plain.length within your loop so you create an infinite loop.
Third, insert inserts BEFORE the index so you need to add 1 to I.
The code below will work for your loop:
Int len = plain.length();
Int count = 0;
for (int i = 0; i < len + count; i++)
{
If (plain[i] == plain[i + 1])
{
plain.insert(plain.begin() + (i +1), 'X');
++count;
}
}
cout << plain;
And as, mentioned below, if you want to handle spaces you can use getline(cin, plain) instead of cin.
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.
Currently I am working on a problem to reformat the inputted string into the odd char then even char with no newline. ex. Input: Good Test. Ouput: Go etodTs. For some reason when I run the program it only outputs a "G".
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <cstdlib>
using namespace std;
int main (int argc, char ** argv) {
char sWordOdd[100] = {0};
scanf("%s", sWordOdd);
int iNum = strlen(sWordOdd);
for (int i=0; i<=iNum && i%2==0; i++) {
printf("%c",sWordOdd[i]);
}
for (int a=0; a<=iNum && a%2!=0; a++) {
printf("%c",sWordOdd[a]);
}
printf("\n");
return 0;
}
Your i<=iNum && i%2==0 break condition terminates your loop early. To achieve the effect you want, put an if statement inside the loop, like so:
for (int i = 0; i <= iNum; i++){
if(i % 2 == 0)
printf("%c",sWordOdd[i]);
}
As for your second loop, I think you meant a++ instead of a--, because otherwise you'll try to access the array using a negative index. I think you meant for your loop to look like this:
for (int a = 0; a <= iNum; a++){
if(a % 2 != 0)
printf("%c",sWordOdd[a]);
}
Side note: Notice the spacing between the variables and the operators in my code. Using spaces like this makes your code easier to read.
int main()
{
string line;
getline(cin, line);
for (size_t start : {0,1})
for (size_t ii = start; ii < line.size(); ii += 2)
cout << line[ii];
cout << endl;
}
The above code handles arbitrarily long lines, is C++11 rather than C, and works.
As said before the loops terminate if i<=iNum && i%2==0 is true (for the first loop), which is the case for i=0. The second loop terminates with i=1.
Since you want to iterate all characters you have to move the i%2==0 part out of the for-statement:
for (int i=0; i<=iNum; i++) {
if (i%2==0)
{
printf("%c",sWordOdd[i]);
}
}
The second loop needs to be modified in the same way...
To fix this problem you have to use a function that can see stuff after whitespaces. This function is called getline. But with getline, you have to use string, so in this example I used string. I then found the size with the .size() function and then using just one constraint for the for loop instead of two in the question. I also took off the char array and replaced it with string as stated above. Everything else is pretty much the same. Using this answer lets me not having to use cstring and also simplifying my code into a short, easy way that is easy to follow through.
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#define Set(a, s) memset(a, s, sizeof (a))
#define Rd(r) freopen(r, "r", stdin)
#define Wt(w) freopen(w, "w", stdout)
using namespace std;
int main (int argc, char ** argv)
{
string sWordOdd;
getline(cin, sWordOdd, '\n');
int iNum = (int)sWordOdd.size();
for (int i=0; i<iNum; i+=2){
cout << sWordOdd[i];
}
for (int a=1; a<iNum; a+=2){
cout << sWordOdd[a];
}
printf("\n");
return 0;
}
Here's a link to the problem I am trying to solve: http://usaco.org/index.php?page=viewproblem2&cpid=187
Here's a link to the solution of the problem: http://usaco.org/current/data/sol_cowfind.html
Here's my solution that I wrote:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string n; int answer = 0;
ifstream fin("cowfind.in");
fin >> n;
fin.close();
int c = 0;
//process for finding the number of possible outputs
for(int i = 0; i < n.size(); i++)
{
if(n[i-1] == '(' && n[i] == '(') //increment the variable c for each pair of "hind" legs
c++;
if(n[i-1] == ')' && n[i] == ')') //increment answer for each pair of front legs
answer++;
}
answer = answer * c; //number of pairs of hind legs * number of pairs of front legs
ofstream fout("cowfind.out");
fout << answer;
fout.close();
return 0;
}
With that being said, what is wrong with my code? It keeps producing incorrect outputs, and I'm not sure why.
Your calculation is incorrect. Lets look at this input: ))((. There is no solution here but your code will produce 1 solution.
Try to iterate the string searching for the first literal ((. Once found - iterate the rest of the string to find )) and add them to the solution sum.
Good luck!