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;
}
Related
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.
#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.
I have written a program below that converts a string to an int and then converts the decimal number to hexadecimal. I'm struggling to check if the hexadecimal consists only of these characters A, B, C, D, E, F, 1, 0. If so set a flag to true or false.
#include<iostream>
#include <stdlib.h>
#include <string>
#include <sstream>
string solution(string &S){
int n = stoi(S);
int answer;
cout << "stoi(\"" << S << "\") is "
<< n << '\n';
//decToHexa(myint);
// char array to store hexadecimal number
string hexaDeciNum[100];
// counter for hexadecimal number array
int i = 0;
while(n!=0)
{
// temporary variable to store remainder
int temp = 0;
// storing remainder in temp variable.
temp = n % 16;
// check if temp < 10
if(temp < 10)
{
hexaDeciNum[i] = temp + 48;
i++;
}
else
{
hexaDeciNum[i] = temp + 55;
i++;
}
n = n/16;
}
// printing hexadecimal number array in reverse order
for(int j=i-1; j>=0; j--){
cout << hexaDeciNum[j] << "\n";
return "";
}
int main() {
string word = "300";
cout << solution(word);
return 0;
}
OK, it is not the exact answer to what you are asking for, but it is a valuable alternative approach for the entire problem of conversion:
char letter(unsigned int digit)
{
return "0123456789abcdefg"[digit];
// alternatively upper case letters, if you prefer...
}
Now you don't have to differenciate... You can even use this approach for inverse conversion:
int digit(char letter)
{
int d = -1; // invalid letter...
char const* letters = "0123456789abcdefABCDEF";
char* l = strchr(letters, letter);
if(l)
{
d = l - letters;
if(d >= 16)
d -= 6;
}
// alternatively upper case letters, if you prefer...
}
Another advantage: This works even on these strange character sets where digits and letters are not necessarily grouped into ranges (e. g. EBCDIC).
How to convert string like 3 word 12 with word to a int only contain number 312 without using stoi in C++? My Codeblode gave me an error stoi is not a member of std when I tried to use it.
Thank you in advance!
Go through the line and skip non-digit symbols. And for digits use -'0' conversion and *10 shift approach. E.G.:
#include <stdio.h>
#include <ctype.h>
//or cctype to use isdigit()
#include <string.h>
//or cstring to use strlen()
int main()
{
char str[] = "3 word 12 with word"; // can be any string
int result = 0; // to store resulting number
// begin of solution
for (int i = 0; i < strlen(str); i++)
{
if (isdigit(str[i]))
{
result *= 10;
result += str[i] - int('0');
}
}
// end of solution
printf("%d\n", result);
return 0;
}
Same idea as in VolAnd's answer. Just, because the question is tagged c++, using some STL stuff.
#include <iostream>
#include <numeric>
#include <string>
using namespace std;
int main(){
std::string input("3 word 12 with word");
int num = std::accumulate(input.begin(), input.end(), 0,
[](int val, const char elem) {
if (isdigit(elem)) {
val = val*10 + (elem-'0');
}
return val;
}
);
std::cout << num << std::endl;
return 0;
}
see http://en.cppreference.com/w/cpp/algorithm/accumulate
note: It gets slightly more interesting if you want to allow a leading minus sign....
And using boost::adaptors::filter(rng, pred) on this one would be fun but slightly overdoing it ;-)
Assuming that s is your initial string.
int toInt(string s) {
string digits;
for(size_t i = 0; i < s.size(); i++)
if(s[i] >= '0' && s[i] <= '9')
digits.push_back(s[i]);
int res = 0;
for(size_t i = 0; i < digits.size(); i++)
res = res * 10 + digits[i] - '0';
return res;
}
Leading zeros are not a problem.
Note however that it is possible to receive an overflow if the resulting digits string will contain a big number.
I'm just a student and I want to know about this array in c++.
How can I display all alphanumeric chars inputted on array k to array n
and all non-alphanumeric on array t?
This what I made, and I don't know what's next
int main(int argc, char *argv[])
{
char k[8], n[8], t[8];
int ctr, nctr, tctr;
for(ctr=0; ctr<8; ctr++){
cout << "Input 1st Element ";
cin >> k[ctr];
if (isalnum(k[ctr]))
#include <string.h>
#include <iostream>
using namespace std;
int main(void) {
char k[8], n[8], t[8];
strcpy(k,"--------");
strcpy(n,"--------");
strcpy(t,"--------");
for (int pos = 0, tcntr = 0, ncntr =0; pos < 8; pos++) {
cout<<"Input your char < : ";
cin>>k[pos];
if (isalnum(k[pos])) {
n[ncntr] = k[pos];
ncntr++;
} else {
t[tcntr] = k[pos];
tcntr++;
}
}
cout<<"Alpha numernic chars ::"<<n<<endl;
cout<<"Non Aplha numberic chars ::"<<t<<endl;
}
Input your char < : 3
Input your char < : ^
Input your char < : d
Input your char < : &
Input your char < : f
Input your char < : 1
Input your char < : 7
Input your char < : 1
Alpha numernic chars ::3df171--
Non Aplha numberic chars ::^&------
how can I display all alphanumeric chars inputted on array k to array n and all non-alphanumeric on array t?
I assume by "display" you mean "copy"? Just use a conditional:
int ctr, nctr = 0, tctr = 0; // note how I explicitly set the counters to 0
for (ctr = 0; ctr < 8; ctr++)
{
cout << "Input Element " << ctr << ": ";
cin >> k[ctr];
if (isalnum(k[ctr]))
{
n[nctr++] = k[ctr];
}
else
{
t[tctr++] = k[ctr];
}
}
If that's not what you wanted, please provide more information.
If it is allowed to use STL, this is when partition_copy is the best solution. You can split array k into two arrays n and t by checking given predicate (whether char is alphanumeric in your case). Like this:
#include <string>
#include <iostream>
#include <algorithm>
using namespace std;
int main(int argc, char *argv[])
{
const size_t len = 8;
char k[len], n[len], t[len];
// Input your data...
// Copy all alphanumeric chars in n and non-alphanumeric to t
partition_copy(k, k + len, n, t, isalnum);
}