atoi() only giving 0 result - c++

#include <iostream>
#include <math.h>
#include <iomanip>
#include <sstream>
#include <stdio.h>
#include <string>
#include <stdlib.h>
using namespace std;
int main()
{
ostringstream str;
double num = pow(2,1000);
int sum = 0;
str << setprecision(1000) << num;
string here = str.str();
cout << here << "\n\n";
/*for(int i = 0; i < here.length(); i++)
{
sum += atoi(&here[i]);
}*/
cout << atoi(&here[0]);
cout << atoi(&here[1]);
cout << atoi(&here[2]);
}
output:
10715086071862673209484250490600018105614048117055336074437503883703510511249361
22493198378815695858127594672917553146825187145285692314043598457757469857480393
45677748242309854210746050623711418779541821530464749835819412673987675591655439
46077062914571196477686542167660429831652624386837205668069376
000
Why all 0s?

Going out on a limb here and assuming you don't actually want to use std::atoi. If you want to sum every digit in a string, you want to convert the digit character into its digit value. The quickest way to do this is to subtract the character constant '0'. In your loop, simply use:
for(int i = 0; i < here.length(); i++)
{
sum += here[i] - '0';
}
This is possible because subtracting the '0' from the various characters in the string results in the numeric value that the character represents.
'0' - '0' == 0
'1' - '0' == 1
'2' - '0' == 2
//etc
'9' - '0' == 9
As far as I can remember, the C++ standard does not force any particular encoding, but it does specify that the digit characters must be contiguous so while the above is safe when the string contains only digits, the subtraction on other characters that may appear in the string will throw off your result:
'E' - '0' == ???
'.' - '0' == ???
'+' - '0' == ???

That's how std::atoi indicates an error. In this case, the error is that the numeric value in the array is larger than the largest possible integer (which is technically undefined behavior with atoi, but your implementation apparently treats it as any other error)

atoi converts a string to an integer (probably 32-bits or 64-bits on your platform).
The number you have stored in here is larger than INT_MAX, so atoi returns zero:
On success, the function returns the converted integral number as an int value. If no valid conversion could be performed, a zero value is returned.
EDIT: actually, didn't even read my own link carefully enough, apparently it's undefined behavior in this case
There is no standard specification on what happens when the converted value would be out of the range of representable values by an int.
from www.cplusplus.com

'here[0]' returns the first character of 'here' as a char.
'&here[0]' returns the address of 'here[0]'. You're not wanting the address. '&' is for getting the address of a variable.
std::atoi(here[0]) returns the first character of here as a char, and converts that char to an int... or would, if 'atoi' handled chars. It doesn't - it handles arrays of chars. Giving it one char probably wouldn't compile.
std::atoi(&here[0]) compiles, but isn't what you want. atoi will keep reading chars until it reaches a null character.
It means that given the string "567321":
std::atoi(&here[0]) would return "987654321"
std::atoi(&here1) would return "87654321"
std::atoi(&here2) would return "7654321"
std::atoi(&here[3]) would return "654321"
... and so on.
If you are really wanting to sum all the numbers, and are required to use std::atoi(), then you can do it using std::string::substr():
for(int i = 0; i < here.length(); i++)
{
std::string subString = here.substr(i,1); //Returns a substring starting at 'i', and including 1 character
sum += atoi(subString.c_str());
}
A better way is to use the method #dreamlax posted... but if you are learning about strings and std::atoi, learning about std::string::substr() is important to know.
If you are using C++11, you'd rewrite it using std::stoi:
for(int i = 0; i < here.length(); i++)
{
std::string subString = here.substr(i,1); //Returns a substring starting at 'i', and including 1 character
sum += std::stoi(subString);
}

Related

how to know if a vector's highest number is even or odd (C++14)

I have this code which gets a string from the user, and it will find the digits and put them in a vector. Then it will find the highest number in the vector.
Question: How should I edit it so it would find if its even or odd?
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <cctype>
using namespace std;
int main() {
string str;
getline(cin, str);
vector<int> vec;
for(int i = 0; i < str.length(); i++){
if(isdigit(str[i])){
vec.push_back(str[i]);
}
}
int max = *max_element(vec.begin(), vec.end());
if(max / 2 == 0){
cout << "is even";
} else {
cout << "is odd";
}
return 0;
}
i want an output such as this:
input:
Hgj326nm2tgh21salamcup
output:
is even
or
input:
eMok2404fggh5987fgf52fgf21
output:
is odd
how to know if a vector's highest number is even or odd
You should replace the statement vec.push_back(str[i]); with:
//-------------------vvvvv----->subtract '0'
vec.push_back(str[i] - '0');
Demo
Explanation
'0' is a character literal. Here both str[i] and '0' will be promoted to int. And the final result that is added(appended) into the vector will be the result of subtraction of those two promoted int values. Moreover, it is guaranteed by the C++ Standard (2.3 Character sets) that:
...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.
This means that the difference between the two will give us the number that the character str[i] represents.
Additionally there is no need for having the following statement:
(int)(vec[i]);//no need for this statement
Also note that if(max / 2 == 0) should be:
//-----v---------->note the modulus
if(max % 2 == 0)
Also refer to Why should I not #include <bits/stdc++.h>?

How to get an easier way of generating the alphabet in C++?

i am trying to make a project,to experiment and learn C++, i didnt finish making it,but what it does is you type in a 3 or 4 (the variable noc) word and the program runs through all the possible (noc) letter words or nonsense, until it finds yours,so there are 2 factors: the length of the word or nonsense and what characters it can type,in my case i just want the alphabet
so here is my code:
#include <iostream>
#include <unistd.h>
using namespace std;
const int noc = 3;
int main() {
string used[noc];
string inp;
cin >> inp;
char albet[] = {'a','b','c'};
cout << "Starting..." << endl;
usleep(1);
string aiput = "";
while(aiput != inp){
for(int i = 0; i <= noc; i++){
aiput = aiput +
}
}
return 0;
}
currently i need the alphabet in the array called 'albet' (i come up with short words for what they mean its easy to forget tho)
so please can you get me a way to generate the alphabet in C++ quickly instead of having to type all of them one by one
When you need a character array you do not have to use individual character literals one by one, as in
char albet[] = {'a','b','c','d','e','f',... uff this is tedious ...};
You can use a string literal instead:
const std::string albet{"abcdefghijklmnopqrstuvwxyz"};
Took me ~10 seconds to type and compared to other answers, this does not rely on ASCII encoding (which is not guaranteed).
You could use std::iota, which is a great algorithm for this use case:
char albet[26] {};
std::iota(std::begin(albet), std::end(albet), 'a');
Here's a demo.
Note that this is not guaranteed to work in c++, unless you have ASCII encoding, but if you can rely on that you'll be fine.
Because all characters can be represented in ASCII codes ('a' starts at 97, all ASCII codes are int), you can simply make a loop to do that. For example:
char albet[26];
for (int ch = 'a'; ch <= 'z'; ch++) {
//do ch-'a' because we start at index 0
albet[ch-'a'] = ch;
}
and you are done!
Each letter has an ASCII representation. More about that here.
They are processed as numbers, being cast, and transformed into characters. For example, the letter a would be represented by the number 97 in decimal.
int aInAscii = 97;
printf("%c", (char)aInAscii);
The upper code would print, as you expect, the letter a. Why? Because we have just converted the number 97 to it's ASCII corresponding character.
So, in this way, we could generate the alphabet, using only numbers. A short example would be here (I preferred casting it before so that the starting and ending points are more clear.
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<char> alphabet;
int aLetterCode = (int)'a'; // ASCII code for letter a (97)
int zLetterCode = (int)'z'; // ASCII code for letter z (122)
for (int charAsciiCode = aLetterCode; charAsciiCode <= zLetterCode; charAsciiCode++) {
alphabet.push_back((char)charAsciiCode);
}
for (char c : alphabet) {
cout << c << " ";
}
return 0;
}
You just can also make a function that returns a char, without generating an array, like this:
char get_alphabet_letter(unsigned int index, bool is_upper = false)
{
char letter = 97 + index;
if(is_upper) return letter - 32;
return letter;
}
from the given below code, you can generate uppercase alphabets of English. Uppercase alphabhets starts in ASCII from A = 65 to Z = 90. And, then, typecast the
integral value of uppercase alphabets into character using char().
#include <iostream>
using namespace std;
int main () {
char a[26];
for (int i=65 ; i<91 ; i++) {
int a[65-i] = char(i);
cout<<a<<endl;
return 0;
}

How to extract numbers used in string?

I've got a std::string number = "55353" and I want to extract the numbers that I've used in this string (5 and 3). Is there a function to do that? If so, please tell me it's name, I've been searching for quite a while now and still haven't found it...
UPD:
I've solved my problem (kinda)
std::string number(std::to_string(num));
std::string mas = "---------";
int k = 0;
for (int i = 0; i < number.size(); i++) {
char check = number[i];
for (int j = 0; j < mas.size(); j++) {
if (check == mas[j])
break;
if (check != mas[j] && check != mas[j+1]) {
mas[k] = check;
k++;
break;
}
}
}
mas.resize(k); mas.shrink_to_fit();
std::string mas will contain numbers that were used in std::string number which is a number converted to std::string using std::to_string().
Try this:
std::string test_data= "55335";
char digit_to_delete = '5';
unsigned int position = test_data.find();
test_data.erase(position, 1);
cout << "The changed string: " << test_data << "\n";
The algorithm is to find the number (as a character) within the string. The position is then used to erase the digit in the string.
Your question looks like homework, so I can guess what you forgot to tell us.
mas starts with ten -. If you spot a 5, you should replace the 6th (!) dash with a '5'. That "6th" is just an artifact of English. C++ starts to count at zero, not one. The position for zero is mas[0], the first element of the array.
The one tricky bit is to understand that characters in a string aren't numbers. The proper term for them is "(decimal) digits". And to get their numerical value, you have to subtract '0' - the character zero. So '5' - '0' == 5 - the character five minus the character zero is the number 5.

simple change of a character to its bit representation [duplicate]

This question already has answers here:
How to print (using cout) a number in binary form?
(13 answers)
Closed 9 years ago.
Why am I getting an error? It looks pretty straightforward to me. Also, is this the best method for doing what I'm trying to do?
#include <iostream>
#include <string>
int main() {
char j = "J";
std::cout << bitchar(j);
return 0;
}
std::string bitchar(char c) {
std::string s;
unsigned thisdivisor = (unsigned)c;
while (!thisdivisor) {
s += thisdivisor % 2 ? '0' : '1';
thisdivisor /= 2;
}
return s;
}
#include <iostream>
#include <string>
#include <bitset>
int main() {
char j = 'J';
std::cout << std::bitset<8>(j);
return 0;
}
Note:
"J" is a single character C-style string(with a trailing \0),
you should use 'J' for char.
Use std::bitset to print the bit pattern.
Try char j = 'j' instead of ="j" to assign a character to your variable. "j" is a string array.
You forgot to describe the error. Presumably it's something like
‘bitchar’ was not declared in this scope
because you didn't declare the function before you called it in main. Either move the definition of bitchar before main, or add a declaration before or inside main:
std::string bitchar(char c);
Then you'll probably get something like:
invalid conversion from ‘const char*’ to ‘char’
because you're trying to assign a string literal "J" to a character variable. Use a character literal 'J' (with single quotes) instead.
Then you'll find you're not getting any output. That's because while (!thisdivisor) loops as long as the value is zero; so it won't loop at all if you give it a non-zero value. You want while (thisdivisor) (or while (thisdiviser != 0) if you want to be more explicit), to loop while it's not zero.
Then you'll find that the bits are inverted; you want '0' if the modulo result is zero, while your test gives '0' if it is not zero:
s += thisdivisor % 2 ? '1' : '0';
or
s += (thisdivisor % 2 == 0) ? '0' : '1';
Finally, you might want to reverse the string (or build it by prepending rather than appending) to get the more conventional most-significant-bit-first ordering.
Answer 1: Why am I getting these errors
Try char j = 'J', as said by #losifM. The double-quote defines a character array, and you're looking for a single character (single quote).
Answer 2: What's a better way
A better way to do such a thing would be using an std::bitset, then stream it using cout.
//Add this
#include <bitset>
char j = 'j';
std::bitset<8> x(j);
std::cout << x;
Should be self explanatory at that point, but this may help: How to print (using cout) the way a number is stored in memory?
Sidenote:
s += thisdivisor % 2 ? '0' : '1';
should also be
s += thisdivisor % 2 ? '1' : '0';
because if thisdivisor % 2 returns 1 (true), you want it to add 1 to s, and vice-versa.
You are assigning char array (which decay to pointer) to char (J).
And then you initialize std::string with char (should be c-string).

Input C-style string and get the length

The string input format is like this
str1 str2
I DONT know the no. of characters to be inputted beforehand so need to store 2 strings and get their length.
Using the C-style strings ,tried to made use of the scanf library function but was actually unsuccessful in getting the length.This is what I have:
// M W are arrays of char with size 25000
while (T--)
{
memset(M,'0',25000);memset(W,'0',25000);
scanf("%s",M);
scanf("%s",W);
i = 0;m = 0;w = 0;
while (M[i] != '0')
{
++m; ++i; // incrementing till array reaches '0'
}
i = 0;
while (W[i] != '0')
{
++w; ++i;
}
cout << m << w;
}
Not efficient mainly because of the memset calls.
Note:
I'd be better off using std::string but then because of 25000 length input and memory constraints of cin I switched to this.If there is an efficient way to get a string then it'd be good
Aside from the answers already given, I think your code is slightly wrong:
memset(M,'0',25000);memset(W,'0',25000);
Do you really mean to fill the string with the character zero (value 48 or 0x30 [assuming ASCII before some pedant downvotes my answer and points out that there are other encodings]), or with a NUL (character of the value zero). The latter is 0, not '0'
scanf("%s",M);
scanf("%s",W);
i = 0;m = 0;w = 0;
while (M[i] != '0')
{
++m; ++i; // incrementing till array reaches '0'
}
If you are looking for the end of the string, you should be using 0, not '0' (as per above).
Of course, scanf will put a 0 a the end of the string for you, so there's no need to fill the whole string with 0 [or '0'].
And strlen is an existing function that will give the length of a C style string, and will most likely have a more clever algorithm than just checking each character and increment two variables, making it faster [for long strings at least].
You do not need memset when using scanf, scanf adds the terminating '\0' to string.
Also, strlen is more simple way to determine string's length:
scanf("%s %s", M, W); // provided that M and W contain enough space to store the string
m = strlen(M); // don't forget #include <string.h>
w = strlen(W);
C-style strlen without memset may looks like this:
#include <iostream>
using namespace std;
unsigned strlen(const char *str) {
const char *p = str;
unsigned len = 0;
while (*p != '\0') {
len++;
*p++;
}
return len;
}
int main() {
cout << strlen("C-style string");
return 0;
}
It's return 14.