#include <iostream>
#include <random>
#include <string>
#include <chrono>
using namespace std;
string string_maker5000(int length)
{
unsigned seed = std::chrono::steady_clock::now().time_since_epoch().count();
default_random_engine e(seed);
string stringcheese;
for (int i = 1; i <= length; i++)
{
uniform_int_distribution<int> distr(0, 1);
int n = distr(e);
stringcheese = ": ";
stringcheese += n;
}
return stringcheese;
}
int main()
{
string yee = string_maker5000(5);
cout << yee << endl;
}
Whenever I run the program, instead of it outputting 1s and 0s it outputs question mark boxes for the 1s I think, and it appears to output 0s as blanks. I'm not really sure. Makes me think its some type of problem with utf or something.
Integers 0 and 1 are not the same as the digits (characters) '0' and '1'. Try this instead
stringcheese += n + '0';
By adding the integer to the zero digit you convert the integer to the required character.
Related
How do i edit this program for j to contain "1"?
Currently it shows 49 which is the ascii value i think.
#include <iostream>
using namespace std;
main()
{
string i = "123";
int j = i[0];
cout << j;
}
You can do this as shown below:
int main()
{
std::string i = "123";
int j = i[0] - '0'; //this is the important statement
std::cout << j;
}
Explanation
'0' is a character literal.
So when i wrote:
int j = i[0] - '0';
The fundamental reason why/how i[0] - '0' works is through promotion.
In particular,
both i[0] and '0' will be promoted to int. And the final result that is used to initialize variable j on the left hand side will be the resultant of subtraction of those two promoted int values on the right hand side.
And the result is guaranteed by the Standard C++ to be the integer 1 since from C++ Standard (2.3 Character sets)
...In both the source and execution basic character sets, the value of
each character after 0 in the above list of decimal digits shall be
one greater than the value of the previous.
So there is no need to use magic number like 48 etc.
Construct a new string from character.
Convert the substring to integer.
Example:
#include <iostream>
using namespace std;
main() {
string i = "123";
// Method 1, use constructor
string s1(1, i[0]);
cout << s1 << endl;
// Method 2, use convertor
int j = atoi(s1.c_str());
cout << j << endl;
}
The solution is simple , just cast j to char .
Example:
#include <iostream>
using namespace std;
main()
{
string i = "123";
int j = i[0];
cout << char(j);
}
You have to subtract ASCII '0' (48) from the character digit:
#include <iostream>
using namespace std;
int main()
{
string i = "123";
int j = i[0] - 48; // ASCII for '0' is 48
// or
// int j = i[0] - '0';
cout << j;
}
Change j to be a char instead of an int:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string i = "123";
char j = i[0];
cout << j;
}
When I try to compile my code this error pops out:
invalid conversion from 'int' to 'const char*'
My task is to write a program that calculates the sum of numbers with odd index.
Please don't roast me (I'm learning how to code in c++), and give some tips how to fix it and get my code working.
#include <bits/stdc++.h>
#include <cmath>
#include <string>
#include <iostream>
using namespace std;
int main()
{
string text;
cin >> text;
int len = text.length(), sum = 0, number = 0, a = 0;
for (int i = len; i > 0; i++) {
a = text[i];
if (i % 2 == 1) {
number = atoi(a);
sum = sum + number;
}
}
cout << sum;
return 0;
}
Your for loop is incorrect because at the first try it starts at out of range index and increases farther. here :
#include <iostream>
using namespace std;
int main()
{
string text;
cin >> text;
int len = text.length(), sum = 0, number = 0, a = 0;
for (int i = 0; i < len; i++) {
a = text[i];
if (i % 2 == 1) {
number = a - '0';
sum = sum + number;
}
}
cout << sum;
return 0;
}
atoi is a function for converting a string to an integer, but a is a character not a string. That's why you have the error.
Replace atoi(a); with a - '0'. That's a formula for converting a digit character to its integer value.
I see a few issues. The most obvious:
number = atoi(a);
atoi expects a const char *, but a is an int.
Note that it would help if you listed which line produces the error message.
Without trying it, I think you can get rid of the atoi() and just do:
sum += a - '0';
The other choice would be to make a into a string and use text.subst() to just get a single character, then you could do:
sum += atoi (a.c_str());
or
sum += stoi(a);
In programming, there are always a dozen of ways to do the same thing.
Learn to extract functions. This will do your task without converting to string.
int sumOfDigitsInEvenPos(int x, int base = 10) {
x = std::abs(x);
int sum = 0;
while (x) {
sum += x % base;
x /= base * base;
}
return sum;
}
There are more than few mistakes :
starting with declaring 'a' as int.
in Your for loop you are starting with length which should be
length-1.
In for loop again you are using i++ which should be i-- or start with i=0;
When you are getting number why you are taking string as input
taking as int/long should be more convient.
atoi accepts char * not int
try out below code it should solve your problem
#include <bits/stdc++.h>
#include <cmath>
#include <string>
#include <iostream>
using namespace std;
int main()
{
string text;
cin>>text;
int len= text.length();
cout<<len<<endl;
int sum=0,number=0;
char a;
for(int i=len-1;i>0;i--)
{
a=text[i];
if(i%2==1)
{ number= (int)a;
sum = sum+number;
}
}
cout<<sum;
return 0;
}
I think you need to check return code of atoi function, because string consists non only of numeric values.
And length returns size of string, for example 5, but symbols iterates from 0 to 4. text[4] - final symbol.
Hi I'm really new to c++ and I wanted to write a code which receives a number from user and sums its digits and keeps doing that until it gets a one-digit number and returns it as a result. But I noticed that when my number is large (like 15 digits long), the wrong number is stored in the variable i declared for storing user input. What do I do?
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int get_sum(long x) {
cout << x<<endl;
if (x < 10) {
return x;
}
else {
string num_in_str = to_string(x);
long result=0;
for (int i = 0; i < num_in_str.size(); i++) {
int digit = num_in_str[i] - '0';
result += digit;
}
return get_sum(result);
}
}
int main()
{
long input;
cin >> input;
int final_result = get_sum(input);``
cout << final_result;
}
Oh I found out. I had to use uint64_t data type
Integer data types in C++ can store numbers up to certain limit. In particular, depending on platform and compiler, "long" can be 32 or 64 bit, and store up to 2^31-1 or 2^63-1. If you want to process numbers of an arbitrary precision, I'd suggest to read each input as string, and process it character-by character, like this:
#include <cctype>
#include <iostream>
#include <string>
int main()
{
std::string s;
while (std::getline(std::cin, s)) {
// parse string
long sum = 0;
for (std::size_t i = 0; i < s.length(); ++i) {
if (std::isdigit(s[i]))
sum += s[i] - '0';
else
break;
}
std::cout << sum << std::endl;
if (sum < 10) break;
}
return 0;
}
I am making a program and I need to generate all 9 digits numbers which have each digit different to the other digits, the 0 is not a valid digit in this case so I am only considering digits from 1 to 9.
So far I have this solution using random number generation, but I am facing performance issues
using namespace std;
#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <vector>
#include <string>
#include <map>
int main()
{
srand (time(NULL));
int secret;
string number = "";
map <string, bool> m;
int count = 0;
int nine_permutation = 362880;
vector <int> v{0,1,2,3,4,5,6,7,8,9};
int x = 9;
while(count < nine_permutation)
{
for(int i = 0; i < 9; i++)
{
secret = rand() % x +1;
number += to_string(v[secret]);
v.erase(v.begin() + secret);
x--;
}
x = 9;
v = {0,1,2,3,4,5,6,7,8,9};
if(m.count(number) == 0)
{
m[number] = true;
count ++;
}
cout << count << endl;
}
cout << number;
}
So you have 10 digits 0,1,2,3,4,5,6,7,8,9 and number you want to get numbers with nine digits.
I think you can start with 123456789, generate all permutations and then replace each character with '0' which would give set:
{023456789, 103456789, 120456789, 123056789, 123406789, 123450789, 123456089, 123456709, 123456780}. And for each element from this set also generate all permutations.
Something like this:
void allNumbersWithDistinctDigits() {
int idxForZero = 0;
std::string initial("123456789");
std::string local(initial);
do {
while (std::next_permutation(local.begin(), local.end())) {
if (local[0] != '0') {
std::cout << local << std::endl;
}
}
local = initial;
local[idxForZero] = '0';
} while(++idxForZero <= initial.size());
}
Condition if (local[0] != '0') is optional and it gets rid of numbers starting with 0, like: 012345678 which is in fact 8 digits 12345678 or octal number.
First time on stack overflow.
I have this assignment due for class where we have a guessing game where our program has to generate a string of Uppercase letters of n length and n different defined by the user. I got most of my assignment working but when generate the string I am lost with how I could put these conditions in place for it to work.
char create_sequence(){
return rand() % 26 + 65;
}
Do you have any tips?
If you know sequence length, you don't need amount of different characters. This is because you require length <= characters.
To create sequence of n unique characters write a separate function:
vector<char> create_sequence(int n) {
vector<char> letters;
for (char ch = 'A'; ch <= 'Z'; ++ch) {
letters.push_back(ch);
}
vector<char> sequence;
for (int i = 0; i < n; ++i) {
int index = rand() % letters.size();
sequence.push_back(letters[index]);
letters.erase(letters.begin() + index, letters.begin() + index + 1);
}
return sequence;
}
Well, personally I think you are not far from the answer:
rand() % 26 + 65
Will effectively returns an uppercase ASCII letter. As long as you initialize the random seed once srand (time(NULL));, you can then call your instruction as many times as you want to get random values. So all you miss is a simple loop. Here is an example for 5 characters:
#include <iostream>
#include <string>
#include <stdlib.h> /* srand, rand */
#include <time.h> /* time */
char randomChar(){
return rand() % 26 + 65;
}
std::string randomString(int length)
{
srand (time(NULL));
std::string rc("");
for(int i=0; i<length; ++i)
{
rc += randomChar();
}
return rc;
}
int main()
{
std::cout << "Random string (x5) is " << randomString(5) << "\n";
}