Printing numbers from 'char array' how to make them numbers not digits - c++

I have an expression, which is stored in a char array char equation[101];The input is via cin.getline();
I want to print all numbers from the expression, using a function void printAllNumbers(const char* equation)
for example: input : 24cd[*43-28/5*93}9(ks)
output:
24
43
28
5
93
9
How do I go about doing this: I go through the array, and if I find a digit, I print it. However, they come as digits, not as numbers.
void printAllNumbers(const char* equation){
for (int i=0; i < strlen(equation); i++){
if (equation[i]== '1' || equation[i]== '2' || equation[i]== '3' || equation[i]== '4'|| equation[i]== '5'|| equation[i]== '6'|| equation[i]== '7'|| equation[i]== '8'||equation[i]== '9')
cout << equation[i] << endl;
}
}

here some simplified variant using some old-fashioned c-style:
#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <iostream>
int main() {
const int len = 101;
char s[len] = {'\0'};
std::cin.getline(s, len);
int i = 0;
while (i < len) {
char t[len] = {'\0'}; // here will the every next number be extracted
int j = -1;
while (isdigit(s[i]) && i < len && j < len) {
t[++j] = s[i++];
}
if (0 <= j) {
printf("%s\n", t); // just print the number as string. here would the conversion to int, unsisigned int or whatsoever take place
}
++i;
}
}
char t[] holds the string number. you can conver't it to number using the standard library functions.

When you're scanning through the string you can be in one of two states: scanning a number and scanning something that's not a number. When you're scanning a number, accumulate the digits; when you hit something that isn't a number, write out the accumulated value. Like this:
const char *str = "24cd[*43-28/5*93}9(ks)";
bool in_number = false;
int value;
while (*str) {
if (isdigit(*str)) {
if (!in_number) {
in_number = true;
value = *str - '0';
} else {
value += *str - '0';
}
} else if (in_number) {
std::cout << value << '\n';
in_number = false;
}
++str;
}

Try Somthing like this:
#include <sstream>
#include <iostream>
#include <cctype>
int main(int argc, char *argv[])
{
int j=0;
char equation[101]{'2','4','c','d','[','*','4','3','-','2','8','/','5','*','9','3','}','9','(','k','s',')'};
char number[j];
for (int i=0; i < sizeof(equation); i++)
{
if (isdigit(equation[i]))
{
number[j++] = equation[i];
}
}
std::cout << number << std::endl;
}

Related

Return all codes - String

Assume that the value of a = 1, b = 2, c = 3, ... , z = 26. You are given a numeric string S. Write a program to return the list of all possible codes that can be generated from the given string.
For most of the cases this code works but it gives wrong output for inputs which have numbers greater than 26. For eg: 12345.
#include <iostream>
#include <string.h>
using namespace std;
using namespace std;
int atoi(char a)
{
int i=a-'0';
return i;
}
char itoa(int i)
{
char c='a'+i-1;
return c;
}
int getCodes(string input, string output[10000]) {
if(input.size()==0)
{
return 1;
}
if(input.size()==1)
{
output[0]=output[0]+itoa(atoi(input[0]));
return 1;
}
string result1[10000],result2[10000];
int size2;
int size1=getCodes(input.substr(1),result1);
if(input.size()>1)
{
if(atoi(input[0])*10+atoi(input[1])>10&&atoi(input[0])*10+atoi(input[1])<27)
{
size2=getCodes(input.substr(2),result2);
}
}
for(int i=0;i<size1;i++)
{
output[i]=itoa(atoi(input[0]))+result1[i];
}
for(int i=0;i<size2;i++)
{
output[i+size1]=itoa(atoi(input[0])*10+atoi(input[1]))+result2[i];
}
return size1+size2;
}
int main(){
string input;
cin >> input;
string output[10000];
int count = getCodes(input, output);
for(int i = 0; i < count && i < 10000; i++)
cout << output[i] << endl;
return 0;
}
if i give input 12345, the output is:
"
abcde
awde
lcde
l"
instead of :
"
abcde
awde
lcde"
i got it fellow members. i did not initialised the size2 variable to zero. also i didn't use >= operator.
int getCodes(string input, string output[10000]) {
if(input.size()==0)
{
output[0]="";
return 1;
}
if(input.size()==1)
{
output[0]=itoa(atoi(input[0]));
return 1;
}
string result1[10000],result2[10000];
int size2=0;
int size1=getCodes(input.substr(1),result1);
if(input.size()>1)
{
if(atoi(input[0])*10+atoi(input[1])>=10&&atoi(input[0])*10+atoi(input[1])<27)
{
size2=getCodes(input.substr(2),result2);
}
}
int k=0;
for(int i=0;i<size1;i++)
{
output[k++]=itoa(atoi(input[0]))+result1[i];
}
for(int i=0;i<size2;i++)
{
output[k++]=itoa(atoi(input[0])*10+atoi(input[1]))+result2[i];
}
return k;
}
this is the final code for getCodes function. Thanks everyone :)
You can do that more simply with something like this:
#include <utility>
#include <string>
#include <vector>
#include <iostream>
using namespace std;
void getCodesRec(unsigned int num, string& current, vector<string>& result)
{
// First and last chars for the codes
static constexpr char FIRST_CHAR = 'a';
static constexpr char LAST_CHAR = 'z';
if (num == 0)
{
// When there is no more number add the code to the results
result.push_back(current);
}
else
{
// Add chars to the existing code
unsigned int next = num;
unsigned int rem = next % 10;
unsigned int f = 1;
// While we have not gone over the max char number
// (in practice this loop will run twice at most for a-z letters)
while (next > 0 && rem <= (unsigned int)(LAST_CHAR - FIRST_CHAR) + 1)
{
next = next / 10;
if (rem != 0) // 0 does not have a replacement
{
// Add the corresponding char
current.insert(0, 1, FIRST_CHAR + char(rem - 1));
// Recursive call
getCodesRec(next, current, result);
// Remove the char
current.erase(0, 1);
}
// Add another number
f *= 10;
rem += f * (next % 10);
}
}
}
vector<string> getCodes(unsigned int num)
{
vector<string> result;
string current;
getCodesRec(num, current, result);
return result;
}
int main()
{
unsigned int num = 12345;
vector<string> codes = getCodes(12345);
cout << "Codes for " << num << endl;
for (string& code : codes)
{
cout << "* " << code << endl;
}
return 0;
}
Output:
Codes for 12345
* abcde
* lcde
* awde

Detecting if input is a string or an integer

Please tell me what is wrong in my approach.
#include <iostream>
#include <string>
using namespace std;
string datatype(string x) {
for (int k = 0; k < strlen(x.c_str());) {
for (int i = 0; i < 10; i++) {
char z = i;
if (x[k] == z) {
k++;
}
else {
return "string";
}
}
}
return "int";
}
int main() {
string inp;
cin >> inp;
cout << datatype(inp);
}
Whatever i enter, it always returns "string".
I have seen the other questions posted here but please tell me what is wrong in my approach.
The standard library has the isdigit function that tells you if the char is a digit.
Here you check that each char of your input is a digit, as soon as a character that is not a digit is found string is returned, else int.
For example 1234 returns int, sdf returns string.
string datatype(string str) {
for (unsigned char c : str) {
if (!isdigit(c)) {
return "string";
}
}
return "int";
}
Edit:
This solution also handles leading - and +. It will return int for -10 and +10 but returns string for +1+1 or -10+10.
string datatype(string str) {
if (str.size() == 1) {
return isdigit(str[0]) ? "int" : "string";
}
bool isInt = true;
for (int i = 1; i < str.size(); i++) {
isInt = isInt && isdigit(static_cast<unsigned char>(str[i]));
if (!isInt) {
break;
}
}
if (isInt) {
unsigned char c = str[0];
isInt = isInt && (c == '-' || c == '+' || isdigit(c));
}
return isInt ? "int" : "string";
}
First of all Include (cstring) as header since x.c_str is not in iostream and string. Then,
When you are doing char z=i; here you are not storing the character equivalent of i in z but the ascii value of i.
Next, You are returning string at the first mismatch between i and x[k]. You should return string if you cannot find a match with any of the possible 10 digits.
You can have a look at the modified code.
#include <iostream>
#include<cstring>
#include <string>
using namespace std;
string datatype(string x) {
for (int k = 0; k < strlen(x.c_str());k++) {
int flag=0;
for (int i = 0; i < 10; i++) {
// char z = i;
if ((x[k]-'0') == i || (k==0 && x[k]=='-')) {
flag=1;
break;
}
}
if(flag==0)
return "string";
}
return "int";
}
int main() {
string inp;
cin >> inp;
cout << datatype(inp);
}

How to get every possible string of n characters in c++?

I know it is possible to use n nested for loops to get the result. This however isn't very flexible. If I wanted to get every string of n+2 characters I would have to write an extra two for loops.
I'm pretty sure I should use a parameter called n_Letters and use some kind of recursion. Any ideas? This is how my code looks right now. It gives all the 3 character combinations.
#include <iostream>
#include <string>
using namespace std;
void StringMaker(){
for(int firstLetter = 97; firstLetter < 123; firstLetter++){
char a = firstLetter;
for(int secondLetter = 97; secondLetter < 123; secondLetter++){
char b = secondLetter;
for(int thirdLetter = 97; thirdLetter < 123; thirdLetter++){
char c = thirdLetter;
cout << a << b << c << endl;
}
}
}
}
int main() {
StringMaker(); // I could add a parameter n_Letters here
}
This is a simple tree traversal problem that can easily be solved using recursion. Using a counter (count) and accumulator (partial) recur on your function for each letter until count is zero then print partial.
#include <iostream>
#include <string>
void StringMaker(int count, std::string partial = "") {
if (count == 0) {
std::cout << partial << '\n';
}
else {
for (char letter = 'a'; letter <= 'z'; ++letter) {
StringMaker(count - 1, partial + letter);
}
}
}
int main() {
StringMaker(3);
return 0;
}
Edit: It seems their are some concerns with my answer regarding memory allocations. If it's a concern for you, consider this alternative solution. Increment the first character if it isn't 'z', otherwise set it to a and repeat with the the second character. Do this until the last character is set from z to a. This acts as a sort of base 26 counter with count digits.
#include <iostream>
#include <string>
void StringMaker(size_t count)
{
std::string data(count, 'a');
size_t i = 0;
do
{
std::cout << data << '\n';
for (i = 0; i < count; ++i)
{
auto & next_char = data[i];
if (next_char < 'z') {
++next_char;
break;
}
else {
next_char = 'a';
}
}
} while (i != count);
}
int main() {
StringMaker(3);
return 0;
}
Here is my just-for-fun solution:
void StringMaker(int n)
{
int base = ('z' - 'a' + 1);
std::string str(n, '\0');
for(int i = 0; i < int_pow(base, n); ++i)
{
for(int j = 0; j < n; ++j)
{
str[n - j - 1] = 'a' + i / int_pow(base, j) % base;
}
cout << str << '\n';
}
}
Suppose we have i written in numerical system with base 26 (from a to z), so increment i with n = 4 give us aaaa, aaab and so on

Recursive function to generate string does not contain two adjacent identical substring c++

I have a task that is difficult for me to handle. The task is: Create recursive function that can be generate a string of length N (N <= 100), formed by the letters 'A', 'B' and 'C' and does not containing two identical adjacent substring. For example: enter for N = 6 and the program should generate such a string in which no one else to repeated substrings: ABACAB. Wrong strings are: AABACA - because 'A' is to 'A'; ABCBCA - as 'BC' is to 'BC' and ABCABC is also wrong because 'ABC' is to 'ABC'.
I made a version of the program but an iterative way, here is the code:
#include <iostream>
#include <ctime>
using namespace std;
const char letters[] = "ABC";
char generate_rand()
{
return letters[rand() % 3];
}
int check(char *s, int pos)
{
for (int i = 1; i <= (pos + 1)/2; i++)
{
int flag = 1;
for (int j = 0; j < i; j++)
if (s[pos-j] != s[pos-i-j])
{
flag = 0;
break;
}
if (flag)
return 1;
}
return 0;
}
int main()
{
char s[100];
int n;
cout << "enter n: ";
cin >> n;
srand(time(NULL));
for (int i = 0; i < n; i++)
{
do
{
s[i] = generate_rand();
} while (check(s, i));
cout << s[i] << " ";
}
cout << " ok" << endl;
system("pause");
return 0;
}
I think the entrance of the recursive function may need to be the number of characters in the string, which will seek to repeat with an adjacent string and each time increased by 1, but not more than half the length of the original string, but do not know how to do it.
So lets start with a simple recursive function which prints 10 letters but doesn't check anything:
void addLetter(char* buf, int max_length)
{
int len = strlen(buf);
buf[len] = generate_rand();
if (strlen(buf) < max_length)
addLetter(buf);
}
int main()
{
srand(time(NULL)); //I forgot srand!
int max_length = 10; //ask user to input max_length, like you had earlier
char buf[100];
memset(buf,0,sizeof(buf));
addLetter(buf, max_length);
printf("\n%s\n", buf);
return 0;
}
Now lets change the recursive function, get it to check just 1 letter:
void addLetter(char* buf, int max_length)
{
int len = strlen(buf);
buf[len] = generate_rand();
if (len > 0)
{
if (buf[len] == buf[len-1])
buf[len] = 0;
}
if (strlen(buf) < max_length)
addLetter(buf);
}
Next step, check 2 letters with previous ones etc. You should be able to take it from here.

going through a string of characters and extracting the numbers?

Given a string of characters, how can I go through it and assign all the numbers within that string into an integer variable, leaving out all other characters?
I want to do this task when there is a string of characters already read in through gets(), not when the input is read.
unsigned int get_num(const char* s) {
unsigned int value = 0;
for (; *s; ++s) {
if (isdigit(*s)) {
value *= 10;
value += (*s - '0');
}
}
return value;
}
Edit: Here is a safer version of the function.
It returns 0 if s is NULL or cannot be converted to a numeric value at all. It return UINT_MAX if the string represents a value larger than UINT_MAX.
#include <limits.h>
unsigned int safe_get_num(const char* s) {
unsigned int limit = UINT_MAX / 10;
unsigned int value = 0;
if (!s) {
return 0;
}
for (; *s; ++s) {
if (value < limit) {
if (isdigit(*s)) {
value *= 10;
value += (*s - '0');
}
}
else {
return UINT_MAX;
}
}
return value;
}
This is a simple C++ way to do that:
#include <iostream>
#include <sstream>
using namespace std;
int main(int argc, char* argv[]) {
istringstream is("string with 123 embedded 10 12 13 ints", istringstream::in);
int a;
while (1) {
is >> a;
while ( !is.eof() && (is.bad() || is.fail()) ) {
is.clear();
is.ignore(1);
is >> a;
}
if (is.eof()) {
break;
}
cout << "Extracted int: " << a << endl;
}
}
Look up the strtol function from the standard C library. It allows you to find the part of a character array that is a number, and points to the first character that isn't a number and stopped the parsing.
You can use sscanf: it works like scanf but on a string (char array).
sscanf might be overkill for what you want though, so you can also do this:
int getNum(char s[])
{
int ret = 0;
for ( int i = 0; s[i]; ++i )
if ( s[i] >= '0' && s[i] <= '9' )
ret = ret * 10 + (s[i] - '0');
return ret;
}