-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary conversion.cpp
More file actions
53 lines (39 loc) · 1.26 KB
/
binary conversion.cpp
File metadata and controls
53 lines (39 loc) · 1.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include<iostream>
#include<string>
#include<cctype>
using namespace std;
string fake_binary(const string& inputstr) // a string parameter to accept the input string
{
string result; // Initialize an empty string to store the result
for(char c : inputstr) // Iterate through each character in the input string
{
if(isdigit(c)) // check if the character is a digit
{
result += (c < '5') ? '0' : '1'; // Convert digits to 0 if less than 5, otherwise to 1
}
}
// If no digits were found, return a message indicating that
if(result.empty()) {
result = "No digits found in input.";
}
return result;
}
int main() {
string input;
cout << "Enter a string containing digits and non-digit characters: ";
getline(cin, input);
string output = fake_binary(input);
cout << "Converted string: " << output << endl;
return 0;
}
/*
best practice:
#include <string>
std::string fakeBin(std::string str){
for (auto &s : str) // Use a range-based for loop to iterate through each character in the string
{
s = s < '5'?'0':'1'; // Convert each character to '0' if it's less than '5', otherwise to '1'
}
return str;
}
*/