C++ integer digits to line by line - c++

I am working with my project that will convert the integer value to each line.
Example:
23487
Output will be
2
3
4
8
7
I know the code if I will used string, but I think its better if I use integer.
My current code using string:
#include <iostream>
#include <string>
using namespace std;
int main() {
string str("23487");
for (int i = 0; i < str.size(); i++){
cout << str[i] << endl;
}
system("pause");
return 0;
}
Can anyone help me if I use int instead of string?

For integer values larger than 0, you can use this:
void Print(int val)
{
if (val > 0)
{
Print(val/10);
cout << val%10 << endl;
}
}

Try this... This code will print as exactly you want... :)
#include <iostream>
#include <string>
using namespace std;
int main() {
int a=23487,ara[10],i=0,j;
while(a)
{
ara[i++]=a%10;
a/=10;
}
for(j=i-1;j>=0;j--)
cout<<ara[j]<<endl;
return 0;
}

Try
#include <stdio.h>
int main(int argc, char * argv[])
{
int value = 23487;
while(value > 0)
{
int d = value % 10;
value /= 10;
printf("d = %d\n", d);
}
return 0;
}
Note that the digits will be printed backwards.

Related

How to change each specific char to an int in 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'

why does it give me bigger than 4 always?

I am trying to get the numbers bigger than 4 after I loop in every other number, but the problem is that it keeps giving me bigger than 4 even tho the number isn't bigger than 4. thank you!
#include <iostream>
#include <vector>
#include <string>
using namespace std;
bool isvalidcc(const string& s)
{
vector<char> v (s.begin(), s.end());
for(auto i=0 ; i<v.size();i+=2)
{
if (v.at(i)>'4')
{
cout<<v.at(i)<<"bigger than 4"<<endl;
}
else
{
cout<<v.at(i)<<"smaller than 4"<<endl;
}
}
return false;
}
int main()
{
vector<string> cardnumbers = {
"371449635398431"
};
int i;
vector<string>::iterator itr;
for (i = 1, itr = cardnumbers.begin(); itr != cardnumbers.end(); ++itr, i++) {
// cout << i << " "
// << *itr
((isvalidcc(*itr)));
}
return 0;
}
I figured it out
Because v.at(i) is a char instead of an int it converts it into ascii code.
this means u have to convert the char in to an int the right way.
if (v.at(i) - '0' >4)
the - '0' will convert it to an int the right way otherwise it will return the wrong values, u can check this by making a new int variable and cout <<
int n = v.at(i);
cout << n;

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;
}
}

CodeEval, First Non-Repeated Character challenge - Need explanation as to why it fails

I have written a small program in c++ that will take as an input a string. It will then print the first non-repeated character in the string. Below is my code. This is for a challenge on CodeEval.com. The thing is, as far as I can tell, the code works as it's supposed to. But CodeEval.com tells me my code is not correct. Unfortunately, I'm not allowed to see the input they're using, but when used at home, I see no problem. Can anyone tell me if there's anything about my code that does not fit the prompt?
#include <cstdlib>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main(int argc, char *argv[])
{
string input = "";
while(getline(cin, input)){
vector<char> inputVector(input.begin(),input.end());
char firstNonRepeatedChar;
for(int i = 0; i < inputVector.size(); i++){
if((inputVector[i] != inputVector[i + 1]) && (inputVector[i] != inputVector[i - 1])){
firstNonRepeatedChar = inputVector[i];
break;
}
}
cout << firstNonRepeatedChar << "\n";
}
//system("PAUSE");
return EXIT_SUCCESS;
}
EDIT:
This is the code that gave me the right answer, if anyone is wondering. Ben helped me realize that I wasn't answering the question properly based on the prompt.
#include <cstdlib>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int findCharInVector(vector<char>& input, char charToFind);
int main(int argc, char *argv[])
{
string input = "";
while(getline(cin, input)){
vector<char> characters(input.begin(),input.end());
char firstNonRepeatedChar;
for(int i = 0; i < characters.size(); i++){
if(!(findCharInVector(characters, characters[i]) > 1)){
firstNonRepeatedChar = characters[i];
break;
}
}
cout << firstNonRepeatedChar << "\n";
}
//system("PAUSE");
return EXIT_SUCCESS;
}
int findCharInVector(vector<char>& input, char charToFind){
int output = 0;
for(int i = 0; i < input.size(); i++){
if(input[i] == charToFind){
output++;
}
}
return output;
}
Based on the link in the comments, a non-repeated character is one that only appears in the string once. Here is the example given:
yellow // y
tooth // h
Your code:
if((inputVector[i] != inputVector[i + 1]) && (inputVector[i] != inputVector[i - 1])){
firstNonRepeatedChar = inputVector[i];
Is only checking if a character is not repeated consecutively. If it was the way you are thinking, then the example above tooth, the first non-repeated would be t, not h as the example specifies.
Furthermore inputVector[i] != inputVector[i - 1] will cause undefined behavior for i == 0.