1

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;
}
7
  • 1
    futureNum[i] doesn't extend the string if i 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. Sep 13, 2018 at 0:30
  • 1
    I thought std::string could expand on it's own? It does not change size with operator[] you need to tell it to resize. cplusplus.com/reference/string/string/resize
    – drescherjm
    Sep 13, 2018 at 0:35
  • 1
    Or that it at least allocated a lot of memory? No. It does not allocate a lot of memory.
    – drescherjm
    Sep 13, 2018 at 0:37
  • 2
    @user1475369 It can't but not by using operator[]. Try futureNum.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 of std::string. Sep 13, 2018 at 0:37
  • 5
    ^ please use '0' instead of 48
    – M.M
    Sep 13, 2018 at 0:48

1 Answer 1

0

I finally fixed the program by changing futureNum[i]=((num[i]-48)^1)+48; to futureNum.push_back(((num[i]-48)^1)+48);, then replacing futureNum=""; to futureNum.clear();

Thanks to François Andrieux

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.