How to change each specific char to an int in C++ - c++

It might be a really dumb question, but I have tried to look it up, and have googled a bunch, but still can't figure out an easy way...
In C++, saying that using namespace std;:
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
String N;
cin >> N;
}
When user input is 123, N will be "123".
How do I cast '1' to int 1, and '2' to int 2, and '3' to int 3?
I cannot use %.
It would be awesome if I were to use an index approach in the string.
I would like to have a function that receives N and its index as parameters. For instance:
int func(string N, int curr_ind)
{
// change curr_ind of N to a single int
// for instance, "123" and 1, it would return 2.
}

#include <iostream>
#include <string>
int get_digit_from_string(const std::string&s, int idx) {
return static_cast<int>(s[idx] - '0');
}
int main() {
std::string num{"12345"};
for (std::size_t i = 0; i < num.length(); ++i) {
std::cout << get_digit_from_string(num, i) << '\n';
}
}
Just get the character at the index, subtract '0', and cast to int.
The subtraction is necessary, otherwise the character of a digit will be cast to the ASCII value of that character. The ASCII value of '0' is 48.
Output:
❯ ./a.out
1
2
3
4
5
Now, just for fun, let's say you need frequent access to these digits. Ideally, you'd just do the conversion all at once and have these ints available to you. Here's one way of doing that (requires C++20):
#include <algorithm>
#include <iostream>
#include <iterator>
#include <string>
#include <vector>
std::vector<int> get_digits_from_string(const std::string& s) {
std::vector<int> v;
std::ranges::transform(s, std::back_inserter(v),
[](auto c) { return static_cast<int>(c - '0'); });
return v;
}
int main() {
std::string num{"12345"};
std::vector<int> digits = get_digits_from_string(num);
for (auto i : digits) {
std::cout << i << '\n';
}
}
We use the string to create a std::vector where each element is an int of the individual characters. I can then access the vector and get whatever digit I need easily.

Another possibility:
#include <iostream>
#include <string>
int main()
{
std::string input;
std::cin >> input;
// allocate int array for every character in input
int* value = new int[input.size()];
for (int i = 0; i < input.size(); ++i)
{
std::string t(1, input[i]);
value[i] = atoi(t.c_str());
}
// print int array
for (int i = 0; i < input.size(); ++i)
{
std::cout << value[i] << std::endl;
}
delete[] value;
}
Output:
x64/Debug/H1.exe
123
1
2
3

Try this:
int func(string N, int curr_ind)
{
return static_cast<int>(N[curr_ind]-'0');
}
Since the ASCII representation of consecutive digits differs by one, all you need to do to convert a character (char c;) representing a digit to the corresponding integer is: c-'0'

Related

The question is about printing digits of two digit number n, I'm encountering a runtime error

Given a two-digit number n, print both the digits of the number.
Input Format:
The first line indicating the number of test cases T.
Next T lines will each contain a single number ni.
Output Format:
T lines each containing two digits of the number ni separated by space.
Constraints
1 <= T <= 100000
10 <= ni <= 99
Error: Runtime Error (SIGSEGV)
I'm not able to pinpoint, where the problem is in the code as it is working fine for a two numbers while it gives the runtime error for 4 or more numbers.
Is there another way of doing this problem other than using for loop twice?
#include <bits/stdc++.h>
using namespace std;
int main()
{
int t;
int arr[t];
cin>>t;
for(int i=0;i<t;i++)
{
cin>>arr[i];
}
int c;
int b;
for(int i=0;i<t;i++)
{
c=(arr[i]/10);
if(c!=0)
{
b=arr[i]%(c*10);
}
else
{
b=arr[i];
}
cout<<c<<" "<<b<<endl;
}
return 0;
}
Fist, you declare t, but do not initialize it, so it is uninitialized. Trying to use the value leads to undefined behavior.
Second, VLA is not valid C++, see here. You have to use std::vector instead.
Third, you don't need to use an int.
So, you should do:
#include <iostream>
#include <vector>
#include <string>
int main()
{
int t{};
std::cin >> t;
std::vector<std::string> arr(t);
for(int i = 0; i < t; i++)
{
std::cin >> arr[i];
}
for(const auto &i : arr)
{
std::cout << i[0] << ' ' << i[1] << '\n';
}
}

How to know the number of digits in an integer

I'm new to programming, and I'm wondering, how can I know the number of digits in an integer that the user enters? For example: the user enters a number like 123456, how can I know that the user enters 6 digits? I don't want to use a for loop to get user input because I don't want the user to enter each digit after a space or enter.
Right now, I'm converting a number to an array of digits so I can have control over them, but the issue is that I don't know how many digits I should loop over, because I don't know how many digits are in the number.
Can I get the user's input as a string and then use string.length and convert it to an array of digits?
#include <iostream>
using namespace std;
int main()
{
int N;
cin >> N;
while(N--)
{
int num;
cin >> num;
int arr[1000];
for (int i=0 ;i<???;i++)
{
arr.[i]=num%10;
num = num /10;
}
}
}
an easier way to do this is to convert it to a string then count the length of said string
#include <iostream>
#include <string>
using namespace std;
int main() {
int n;
cin >> n;
string str = to_string(n);
cout <<"the length of" <<str << "is:" <<str.length() <<"\n";
}
typing in a 41 will print out.
the length of 41 is 2
while (num != 0)
{
arr.[i]=num%10;
num = num /10;
}
is a common pattern that's close to what you already have.
Although you can do what you mentioned in your question and someone suggested in the comments and get the input as a string and use string.length.
Yes, you can read in the user's input as a std::string instead of as an int, and then you can use std::string::size() (or std::string::length()) to get the number of characters in the string, eg:
#include <iostream>
#include <string>
int main()
{
std::string S;
std::cin >> S;
int arr[1000] = {};
for (size_t i = 0; i < S.size(); ++i)
{
arr[i] = (S[i] - '0');
}
return 0;
}
Alternatively:
#include <iostream>
#include <string>
#include <algorithm>
int main()
{
std::string S;
std::cin >> S;
int arr[1000] = {};
std::transform(S.begin(), S.end(), arr, [](char ch){ return int(ch - '0'); });
return 0;
}
Either way, if needed, you can check if the std::string represents a valid integer using std::stoi() or std::strtol() or other similar function, or by putting the std::string into a std::istringstream and then reading an integer from it.
Otherwise, you can read the user's input as an int and then convert it to a std::string for processing:
#include <iostream>
#include <string>
int main()
{
unsigned int N;
std::cin >> N;
std::string S = std::to_string(N);
int arr[1000] = {};
for (size_t i = 0; i < S.size(); ++i)
{
arr[i] = (S[i] - '0');
}
// or:
// std::transform(S.begin(), S.end(), arr, [](char ch){ return int(ch - '0'); });
return 0;
}
Otherwise, if you really want to read in an int and loop through its digits directly, you can use something more like this:
#include <iostream>
int main()
{
unsigned int N;
std::cin >> N;
int arr[1000] = {};
size_t i = 0;
while (N != 0)
{
arr[i++] = num % 10;
num /= 10;
}
return 0;
}

C++ string array about nums

Say the strings is "Asah1234&^%736hsi)(91",
than storage 1234,736,91 in three arrays
In general,i want to put each continuous nums in each array.
Queations: how many arrays i will need,what's the size of each group of numbers,how to make the loop.
I want to write a fuction to do it.
#include<iostream>
using namespace std;
void splitString(string str)
{
string num;
for (int i = 0; i < str.length(); i++)
{
if (isdigit(str[i]))
num.push_back(str[i]);
}
cout << num << endl;
}
int countnum( string str)
{
string num;
int sum = 0;
for (int i = 0; i < str.length(); i++)
{
if (isdigit(str[i]))
sum++;
}
cout << sum << endl;
return 0;
}
int main()
{
const int MAXLEN = 100;
char str[MAXLEN];
printf("please enter strings:");
scanf_s("%s", str, MAXLEN);
splitString(str);
countnum( str);
return 0;
}
Maybe I have a misunderstanding here. Then please comment and I will delete the answer.
This is a standard task and will be solved with a regex. It is just the definition of a variable and initialzing this variable with its range constructor. So, a one-liner.
There is no further statement needed.
Please see:
#include <iostream>
#include <string>
#include <regex>
#include <vector>
std::regex re{ R"(\d+)" };
int main() {
// The input string with test data
std::string test{"Asah123&^%736hsi)(918"};
// Define a variable numbers and use the range constructor to put all data in it
std::vector numbers(std::sregex_token_iterator(test.begin(), test.end(), re), {});
// Show the result on the screen
for (const auto& n : numbers) std::cout << n << "\n";
return 0;
}

Displaying all prefixes of a word in C++

I am trying to do is display all the suffixes of a word as such:
word: house
print:
h
ho
hou
hous
house
What I did is:
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
char cuvant[100];
int i,k;
cin>>cuvant;
for(i=0;i<strlen(cuvant);i++)
{
for(k=0;k<i;k++)
{
if(k==0)
{
cout<<cuvant[k]<<endl;
}else
{
for(k=1;k<=i;k++){
if(k==i) cout<<endl;
cout<<cuvant[k];
}
}
}
}
}
What am I doing wrong?
You're over-complicating it. Here's a simpler way:
#include <iostream>
#include <string>
#include <string_view>
int main() {
std::string s;
std::cin >> s;
for (std::string::size_type i = 0, size = s.size(); i != size; ++i)
std::cout << std::string_view{s.c_str(), i + 1} << '\n';
}
If you don't have access to a C++17 compiler, you can use this one:
#include <algorithm>
#include <iostream>
#include <iterator>
#include <string>
int main() {
std::string s;
std::cin >> s;
for (auto const& ch : s) {
std::copy(s.c_str(), (&ch + 1),
std::ostream_iterator<decltype(ch)>(std::cout));
std::cout << '\n';
}
}
Even so, I think it would be better for your learning progress to use a debugger to finger out the problem yourself. Here the problems with your code:
For the i=0 (the first iteration of your outer loop) the for(k=0;k<i;k++) will not be executed at all, as k<0 evaluates to false.
And having a running variable (k) that you change in two for loops that are nested, is most of the time also an indication that something is wrong.
So what you want to do: You want to create each possible prefix, so you want to create n strings with the length of 1 to n. So your first idea with the outer loop is correct. But you overcomplicate the inner part.
For the inner part, you want to print all chars from the index 0 up to i.
int main() {
char cuvant[100];
std::cin >> cuvant;
// loop over the length of the string
for (int i = 0, size = strlen(cuvant); i < size; i++) {
// print all chars from 0 upto to i (k<=0)
for (int k = 0; k <= i; k++) {
std::cout << cuvant[k];
}
// print a new line after that
std::cout << std::endl;
}
}
But instead of reinventing the wheel I would use the functions the std provides:
int main() {
std::string s;
std::cin >> s;
for (std::size_t i = 0, size = s.size(); i < size; i++) {
std::cout << s.substr(0, i + 1) << std::endl;
}
}
For this very simple string suffix task you can just use:
void main()
{
std::string s = "house";
std::string s2;
for(char c : s)
{
s2 += c;
cout << s2 << endl;
}
}
For more complicated problems you may be interested to read about Suffix Tree
Your code is wrong, the following code can fulfill your requirements
#include <iostream>
using namespace std;
int main()
{
char cuvant[100];
int i,k;
cin>>cuvant;
for(i=0;i<strlen(cuvant);i++)
{
for (k = 0; k <= i; ++k)
{
cout<<cuvant[k];
}
cout<<endl;
}
}

How to convert numbers into vector of integers?

I want my program to ask the user to input any number and then store it into a std::vector where every single digit is allocated to a separate vector index:
input: 142
output vector: [1, 4, 2]
I tried this:
int main()
{
std::vector<int> v;
int number;
cin >> number;
for(unsigned int i = 100; i > 0; i/=10)
{
v.push_back(number/i);
number -= (number/i)*i;
}
for(size_t i = 0; i < v.size(); ++i)
{
std::cout<<v[i]<<std::endl;
}
}
It works. But what should I do when the input-length is unknown?
Use simply std::string and for each char(which is actually integers) of string convert to integer as follows: SEE LIVE HERE
#include <iostream>
#include <vector>
#include <string>
int main()
{
std::vector<int> v;
std::string number = "123456789987654321";
for(auto& Integer: number)
v.emplace_back(static_cast<int>(Integer - '0'));
for(const auto& it: v) std::cout << it << " ";
}
Output:
1 2 3 4 5 6 7 8 9 9 8 7 6 5 4 3 2 1
In case of entering unwanted characters/ user inputs(for example some negative numbers or even this: +-1234567), you can go for something with try-catch. try to convert the char to int, otherwise skip in the catch block as follows. SEE LIVE HERE
#include <iostream>
#include <vector>
#include <string>
#include <exception>
int main()
{
std::vector<int> v;
std::string number = "+-1234567";
for(auto& Integer: number)
{
std::string Char(1, Integer); // convert to string
try { v.emplace_back(std::stoi(Char)); }
catch(...) { continue; } // any case of exceptions
/* or using much simpler std::isdigit from <cctype>
by which conversion to std::string and try-catch can be avoided.
if(std::isdigit(Integer))
v.emplace_back(static_cast<int>(Integer - '0'));
*/
}
for(const auto& it: v) std::cout << it << " ";
}
Output:
1 2 3 4 5 6 7
Edte: As per #Aconcagua suggested, included the solution with std::isdigit
while(number) {
v.push_back(number%10);
number /= 10;
}
std::reverse(v.begin(), v.end());
Change the for initilization unsigned int i = number rather than unsigned int i = 100. The re-written for statement will be:
for(unsigned int i = number; i > 0; i/=10)
I you want to stay with digits and std::deque is an option you could do the following:
int main()
{
std::deque<int> v;
int number;
cin >> number;
while(number != 0)
{
v.push_front(number%10);
number = number/10;
}
for(size_t i = 0; i < v.size(); ++i)
{
std::cout<<v[i]<<std::endl;
}
return 0;
}
With the modulo operator you simply take the last digit and insert it in the front of the deque. Afterwards you "cut off" that digit with /10.
I used a deque, because you can't push front with vectors.