1

We were given an input which we have to store in vector and do something. The input was like this

123

Now I'm currently working on it to understand the basics and working of vector like i have learned the arrays in C lang & python. Here's what I have implemented;

#include<bits/stdc++.h>
 using namespace std;

int main()
{
vector<int> v1;
  string x;
 getline(cin,x);    //takes input as string

stringstream s(x);

int temp;

for(int i=0;i<x.size();i++)
{
    char j=x[i];    //Iterating over each n every string
    int num;
    stringstream ss;
    ss<<j;
    ss>>num;     //covert the string to integer
    v1.push_back(num);
}

for(auto i=v1.begin();i!=v1.end();++i)    //output
    cout<<*i<<" ";
return 0;

}

After runnung this i will get output of vector like this:

1 2 3

Is there any easy way to implement this like in python we use .split()?

desertnaut
  • 57,590
  • 26
  • 140
  • 166
Joel_RDJ
  • 13
  • 5
  • So you want to split each digit apart? – silverfox Jun 22 '21 at 07:21
  • Just to be clear: You want to take a string like `"123"` as input and store the numeric value of each digit in a `vector`? Or is there any further logic to it? – Lukas-T Jun 22 '21 at 07:22
  • In Python, `"123".split()` is not `["1", "2", "3"]`. – molbdnilo Jun 22 '21 at 07:32
  • It's very difficult to tell whether there is a better way without a better description than "an input which we have to store in vector and do something" of what the program is supposed to do. – molbdnilo Jun 22 '21 at 07:34
  • Thank u Guys my question has been resolved ,Please read the below comments!Sorry for my poor explanation I'm new to SO . – Joel_RDJ Jun 22 '21 at 07:49

3 Answers3

2

If it's guaranteed that the input only consists of digits only, then you can use std::cin to input, then minus each character by '0' to get the integer.

#include <iostream>
#include <vector>
#include <string>

int main()
{
    std::string inp;
    std::cin >> inp;

    std::vector<int>result;
    for (char c : inp) { result.push_back(c - '0'); }
    for (int x : result) {std::cout << x << " ";}
}

Result:

1237790
1 2 3 7 7 9 0

Else you can use std::getline (so some spaces maybe added to the input) to input, then use isdigit() to check whether a character is a digit :

#include <iostream>
#include <vector>
#include <string>

int main()
{
    std::string inp;
    std::getline(std::cin, inp);

    std::vector<int>result;
    for (char c : inp)
    {
        if (isdigit(c)) {result.push_back(c - '0');}
    }
    for (int x : result) {std::cout << x << " ";}
}

Result:

abc  123 /*78awd00
1 2 3 7 8 0 0

Some explanation :

In C++ programming language, the char data type is an integral type, meaning the underlying value is stored as an integer. More specifically, the integer stored by a char variable are interpreted as an ASCII character : ASCII table.

As you can see, digit char is represented from 48 to 57, starting from '0' and ending with '9'.

So when we take a digit char c, for example '2', and minus it by '0', we're quite literally substracting the ASCII value of '2', which is 50, to '0', which is 48, and we end up with an integer that we needed : 2.

Similar post : Convert a character digit to the corresponding integer in C

So you can see that using stringstream instead of a simple substraction is quite an overkill (but it works anyway, no objection there):

char j=x[i]; 
int num;
stringstream ss;
ss<<j;
ss>>num;

Note that using namespace std; and #include <bits/stdc++.h> is highly warned against:

silverfox
  • 1,568
  • 10
  • 27
  • U r real gem thankssss for replying.Also Thanks*1000 for elite level explanation.My all doubts are totally destroyed after reading ur each n every line...... – Joel_RDJ Jun 22 '21 at 07:43
1

I didn't test it, but conceptually could look like that

#include<bits/stdc++.h>
using namespace std;

int main()
{
    string num_str; // will hold the whole number as string
    cin >> num_str;
    vector<int> digits;
    for(auto digit_ch : num_str) {
        digits.push_back(digit_ch - '0');
    }
}

The trick is in this line digits.push_back(digit_ch - '0'); where you iterate every digit as a char (like '2' or '5'), and by subtracting '0' from it, you get a numerical value of this digit (2 and 5 respectively)

Alexey S. Larionov
  • 6,555
  • 1
  • 18
  • 37
  • Wooooowwww.......Cant belive my eyes, wht i did in 50 lines u did that in 10 line.Thank u soo much for replying!!!!! Really liked ur code,Short n sweer – Joel_RDJ Jun 22 '21 at 07:45
  • 1
    @Joel_RDJ By the way in competitive programming it's sometimes useful when you have alphabet characters which define order, and you can easily convert `ABC...XYZ` into `0 1 2 ... 23 24 25` by again subtracting from each char `A`. This trick uses the fact that in [ASCII table](http://www.asciitable.com/) capital letters are represented in a sequence, so e.g. code for `A` is 65, and for `B` it's 66 and so on. By subtracting `A` from another capital letter, you essentially get how far away this letter is from `A` in ASCII table (so `A` is 0 away from `A`, `B` is 1 away from `A` as so on) – Alexey S. Larionov Jun 22 '21 at 07:52
1

Another option is std::for_each which can iterate over each character in inp and then with the use of a lambda, check if the character is a digit, and if so, add it to result, e.g.

    std::for_each (inp.begin(), inp.end(), [&result](int c) { 
                                            if (isdigit(c)) 
                                                result.push_back(c - '0');
                                            });

The example validating the input and using std::for_each() could be:

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>

int main()
{
    std::string inp;
    std::vector<int>result;
    
    if (std::getline (std::cin, inp)) {
        std::for_each (inp.begin(), inp.end(), [&result](int c) { 
                                                if (isdigit(c)) 
                                                    result.push_back(c - '0');
                                                });
    }
        
    for (int x : result) {
        std::cout << x << " ";
    }
    std::cout.put ('\n');
}

Example Use/Output

$ echo "1 2 3 4 5" | ./bin/for_each_digit
1 2 3 4 5
David C. Rankin
  • 81,885
  • 6
  • 58
  • 85
  • Sure, glad to help, there are many, many ways this can be handled. None, necessarily better than the other so long as they are relatively efficient and correct. – David C. Rankin Jun 22 '21 at 08:12