Okay, here is the same thing using an array. Commented.
Code:
#include <iostream>
int main()
{
//char array 0-255
char buf[256];
std::cout << "Enter a binary number: ";
std::cin >> buf;
std::cin.ignore();
//Loop through each character in the buffer
for ( int i = 0; i != 255; ++i )
{
//If character at index 'i' is '\0' then we know it is the end of the string
if ( buf[i] == '\0' )
break;
//self explanatory
if ( buf[i] == '1' )
buf[i] = '0';
else if ( buf[i] == '0' )
buf[i] = '1';
else
{
//Display a message and exit if any character besides '1' or '0' are found
std::cout << "Error: Buffer contains invalid data" << std::endl;
std::cin.get();
return 1;
}
}
//Output the result
std::cout << "One's Complement: " << buf << std::endl;
std::cin.get();
}
Generally with C++ you can avoid using arrays most of the time, but it is still good to know about them.
Feel free to ask if there is anything there that you dont understand.
Edit: This is the exact same program just using std::string, and std::string::iterator instead of a char array
Code:
int main()
{
std::string buf;
std::string::iterator iter;
std::cout << "Enter a binary number: ";
std::getline(std::cin, buf);
//Loop through each character in the buffer
for ( iter = buf.begin(); iter != buf.end(); ++iter )
{
//self explanatory
if ( (*iter) == '1' )
(*iter) = '0';
else if ( (*iter) == '0' )
(*iter) = '1';
else
{
//Display a message and exit if any character besides '1' or '0' are found
std::cout << "Error: Buffer contains invalid data" << std::endl;
std::cin.get();
return 1;
}
}
//Output the result
std::cout << "One's Compliment: " << buf << std::endl;
std::cin.get();
}