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: