I am trying to create a program that when you input 1 or 0, it will flip it to the opposite number, and append it to the end. It should then repeat this process with the entire number.
Example:
Input - 1
Iterations - 3
Expected output - 10010110
Actual output - 1
#include <iostream>
#include <string>
std::string num;
std::string futureNum;
int iterations = 1;
int main()
{
std::cout << "number to start with (1 or 0)";
getline (std::cin, num);
std::cout<<"\nIterations:";
std::cin>>iterations;
while (iterations > 0) {
for(int i = 0;i<=num.length();i++)
{
futureNum[i]=((num[i]-48)^1)+48;
}
num.append(futureNum);
futureNum="";
iterations--;
}
std::cout<<num<<std::endl;
}
futureNum[i]
doesn't extend thestring
ifi
exceeds the bounds of the string. It's undefined behavior, you are not allowed to try to access elements beyond the end of the string.operator[]
you need to tell it to resize. cplusplus.com/reference/string/string/resizeoperator[]
. TryfutureNum.push_back(((num[i]-48)^1)+48);
instead.push_back
is one of the members that will automatically grow the string as needed. Take a moment to familiarize with the features ofstd::string
.'0'
instead of48