This question already has answers here:
Convert char to int in C and C++
(14 answers)
Closed 9 years ago.
My code is this:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main() {
int a;
cout << "Enter a number" << endl;
cin >> a;
string a_str;
ostringstream temp;
temp << a;
a_str = temp.str();
for(int i = 0; i < a_str.length(); i++) {
char c = a_str[i]; //How this character convert to integer number
}
system("pause");
return EXIT_SUCCESS;
}
How char c convert to int ?
I need this for
I need this because I need to get the highest digit
If you want to get char '8' to int 8 for example, this would be enough for ascii
int i = a_str[0] - '0';
const int i = atoi(&c);
should work too
char is already an integral type. I think you meant the following
char c = a_str[i] - '0';
atoi(c) for integers
atof(c) for floats
do the trick
You can also write it yourself:
This works for normal keys (not arrows keys or...)
#include <iostream>
using namespace std;
int main () {
char c;
cin >> c;
cout << (int)c << endl;
}
if you just have digits, you can do this:
int num = c - '0';
Related
This question already has answers here:
Convert char to int in C and C++
(14 answers)
Closed 1 year ago.
could someone try explain the what the difference between these two pieces of codes is?
// Example program
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
char keypad[10][5]={"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
int idx = 2;
string digits = "1324";
int curidx=digits[idx] - '0';
cout << curidx << endl;
}
In this case, with the inclusion on line 12, the output is 2.
// Example program
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
char keypad[10][5]={"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
int idx = 2;
string digits = "1324";
int curidx=digits[idx];// - '0';
cout << curidx << endl;
}
In this result, the output result is 50. What does the inclusion of - '0' do?
In C and Cpp, everything is inherently treated as a "number". Even char manipulations should be treated as number-operations...that makes it easier to logic-out the requirements.
Every char is indeed, an integer, equivalent to its ASCII value.
Hence, '2' = 50. Also, 'A' = 65 and 'a' = 97 and so on...
So, your operation '2' - '0' actually does 50-48, which results in 2
When you do not subtract and print '2' as integer, it prints its ascii value, which is 50. If you would print it as a char or string, it would have printed 2.
I have a homework assignment. The input is a three-digit number. Print the arithmetic mean of its digits. I am new to C++ and cannot write the code so that it takes 1 number as input to a string. I succeed, only in a column.
#include <iostream>
int main()
{
int a,b,c;
std::cin >> a >> b >> c;
std::cout << (a+b+c)/3. << std::endl;
return 0;
}
If you write it in Python it looks like this. But I don't know how to write the same thing in C ++ :(
number = int(input())
digital3 = number % 10
digital2 = (number//10)%10
digital1 = number//100
summ = (digital1+digital2+digital3)/3
print(summ)
The most direct translation from Python differs mostly in punctuation and the addition of types:
#include <iostream>
int main()
{
int number;
std::cin >> number;
int digital3 = number % 10;
int digital2 = (number/10)%10;
int digital1 = number/100;
int summ = (digital1+digital2+digital3)/3;
std::cout << summ << std::endl;
}
In your code, you use three different numbers and take the mean of their sum (not the sum of three-digits number). The right way is:
#include <iostream>
int main()
{
int a;
std::cin >> a;
std::cout << ((a/100) + ((a/10)%10) + (a%10))/3.<< std::endl;
return 0;
}
EDIT: This answer is incorrect. I thought the goal was to average three numbers. Not three DIGITS. Bad reading on my part
*Old answer *
I'm not sure I'm interpreting the question correctly. I ran your code
and confirmed it does what I expected it to...
Are you receiving three digit chars (0-9) and finding the average of
them? If so, I'd trying using a
for loop using getChar()
Here is a range of functions that may be of use to you.
Regex strip
Convert string to int: int myInt = stoi(myStr.c_str())
Convert int to string: std::string myStr = myInt.to_string()
If you need to improve your printing format
Using printf
If using cout, you can kindve hack your way through it!
The input is a three-digit number.
If it means, you'll be given a number that will always have 3 digits, then you can try the following approach.
Separate each digit
Find all digits sum
Divide the sum by 3
If you're given the number as a string, all you've to do is convert that string into int. Rest of the approach is the same as abve.
Sample code:
int main()
{
int a;
std::cin >> a;
int sum = (a % 10); // adding 3rd digit
a /= 10;
sum += (a % 10); // adding 2nd digit
a /= 10;
sum += (a % 10); // adding 1st digit
std::cout << (double)sum / 3.0 << std::endl;
return 0;
}
Here's a possible solution using std::string:
EDIT added digits check
#include <iostream>
#include <string>
#include <cctype>
int main()
{
std::string s;
std::cin >> s;
if(s.length() == 3 && isdigit(s[0]) && isdigit(s[1]) && isdigit(s[2]))
{
std::cout<<double(s[0] + s[1] + s[2])/3 - '0'<<std::endl;
}
else
{
std::cout<<"Wrong input"<<std::endl;
}
return 0;
}
I'm working on this code that takes a numeric string and fills an array with each "digit" of the string. The issue I'm having is trying to convert an integer to a string. I tried using to_string to no avail.
Here is the code (note this is pulled from a larger program with other functions):
#include <cstdlib>
#include <stdlib.h>
#include <iostream>
#include <time.h>
#include <typeinfo>
int fillarr(int &length) {
int arr[length];
string test = "10010"; //test is an example of a numeric string
int x = 25 + ( std::rand() % ( 10000 - 100 + 1 ) );
std::string xstr = std::to_string(x); //unable to resolve identifier to_string
cout << xstr << endl;
cout << typeid (xstr).name() << endl; //just used to verify type change
length = test.length(); //using var test to play with the function
int size = (int) length;
for (unsigned int i = 0; i < test.size(); i++) {
char c = test[i];
cout << c << endl;
arr[int(i)] = atoi(&c);
}
return *arr;
}
How can I convert int x to a string? I have this error: unable to resolve identifier to_string.
As mentioned by user 4581301, you need an #include <string> to use string functions.
The following, though is wrong:
arr[int(i)] = atoi(&c);
The atoi() will possibly crash because c by itself is not a string and that mean there will be no null terminator.
You would have to use a buffer of 2 characters and make sure the second one is '\0'. Something like that:
char buf[2];
buf[1] = '\0';
for(...)
{
buf[0] = test[i];
...
}
That being said, if your string is decimal (which is what std::to_string() generates) then you do not need atoi(). Instead you can calculate the digit value using a subtraction (much faster):
arr[int(i)] = c - '0';
Okay I modified my code a bit per suggestion from everyone and ended up handling the conversion like this:
string String = static_cast<ostringstream*>( &(ostringstream() << x) )->str();
cout << String << endl;
I am writing a program that asks the user to type in a very large int (much larger than the type int can handle). When receive this int from the user, it is stored in a string. Then, I want to convert this string into an int array (I am using a dynamic int array). After compiling and running the program, I get values that don't make sense. The values of my int array seem to be random gibberish. I don't see why this is so - it doesn't look like my loops are out of bound in the converting process. Please help. The purpose of creating an int array is to then come up with ways to add, subtract, multiply, and compare very large int values. To make it clear what I am intending to do: say the user types in "12345". I want to store this string value into an int array that would have a length of 5, each element corresponding to the next number in the int.
largeIntegers.h
#ifndef H_largeIntegers
#define H_largeIntegers
#include <iostream>
#include <string>
class largeIntegers
{
private:
void readInteger();
// reads integer
public:
std::string s_integer;
int* integer;
int length;
largeIntegers();
// default constructor
void outputInteger();
// outputs integer
};
#endif
largeIntegers.cpp
#include <iostream>
#include <string>
#include "largeIntegers.h"
using namespace std;
largeIntegers::largeIntegers()
{
readInteger();
}
void largeIntegers::readInteger()
{
int i = 0,j = 0, k;
cout << "Enter large integer: ";
cin >> s_integer;
for (; s_integer[i] != '\0'; i++);
length = i;
int* integer = new int[i];
k = 0;
for (j = i - 1; j >= 0; j--)
integer[j] = s_integer[k++] - 48;
}
void largeIntegers::outputInteger()
{
for (int i = length - 1; i >= 0; i--)
cout << integer[i];
}
User.cpp
#include <iostream>
#include <string>
#include "largeIntegers.h"
using namespace std;
int main()
{
largeIntegers a;
cout << a.length << endl << endl;
cout << a.integer[0] << endl << a.integer[1] << endl;
a.outputInteger();
cout << endl << endl;
return 0;
}
I intentionally made the variables in the header public for debugging purposes. My output on the console after compiling is:
Enter large integer: 111
3
952402760
1096565083
10966961571096565083952402760
This is the problem
int* integer = new int[i];
change to
integer = new int[i];
Your version declares a local variable that just happens to have the same name as your class variable. Easy mistake to make.
also, using standards facilities like std::vector and std::getline would make your code much cleaner in addition to avoid the problem you had, and resolve memory leaks you have now if you call readInterger twice:
void largeIntegers::readInteger()
{
cout << "Enter large integer: ";
std::getline(std::cin, s_integer);
integer = std::vector(s_integer.size());
//your last loop to fill the array probably can be replaced by std::transform
}
I want to make a program that will read some number in string format and output it like this: if the number is 12345 it should then output 12 23 34 45 . I tried using the substr() function from the c++ string library, but it gives me strange results - it outputs 1 23 345 45 instead of the expected result. Why ?
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
int main(void)
{
string a;
cin >> a;
string b;
int c;
for(int i=0;i<a.size()-1;++i)
{
b = a.substr(i,i+1);
c = atoi(b.c_str());
cout << c << " ";
}
cout << endl;
return 0;
}
If I am correct, the second parameter of substr() should be the length of the substring. How about
b = a.substr(i,2);
?
As shown here, the second argument to substr is the length, not the ending position:
string substr ( size_t pos = 0, size_t n = npos ) const;
Generate substring
Returns a string object with its contents initialized to a substring of the current object. This substring is the character sequence that starts at character position pos and has a length of n characters.
Your line b = a.substr(i,i+1); will generate, for values of i:
substr(0,1) = 1
substr(1,2) = 23
substr(2,3) = 345
substr(3,4) = 45 (since your string stops there).
What you need is b = a.substr(i,2);
You should also be aware that your output will look funny for a number like 12045. You'll get 12 20 4 45 due to the fact that you're using atoi() on the string section and outputting that integer. You might want to try just outputing the string itself which will be two characters long:
b = a.substr(i,2);
cout << b << " ";
In fact, the entire thing could be more simply written as:
#include <iostream>
#include <string>
using namespace std;
int main(void) {
string a;
cin >> a;
for (int i = 0; i < a.size() - 1; i++)
cout << a.substr(i,2) << " ";
cout << endl;
return 0;
}
Another interesting variant question can be:
How would you make "12345" as "12 23 34 45" without using another string?
Will following do?
for(int i=0; i < a.size()-1; ++i)
{
//b = a.substr(i, 2);
c = atoi((a.substr(i, 2)).c_str());
cout << c << " ";
}
substr(i,j) means that you start from the index i (assuming the first index to be 0) and take next j chars.
It does not mean going up to the index j.
You can get the above output using following code in c
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
char *str;
clrscr();
printf("\n Enter the string");
gets(str);
for(int i=0;i<strlen(str)-1;i++)
{
for(int j=i;j<=i+1;j++)
printf("%c",str[j]);
printf("\t");
}
getch();
return 0;
}
Possible solution without using substr()
#include<iostream>
#include<string>
using namespace std;
int main() {
string c="12345";
int p=0;
for(int i=0;i<c.length();i++) {
cout<<c[i];
p++;
if (p % 2 == 0 && i != c.length()-1) {
cout<<" "<<c[i];
p++;
}
}
}
Possible solution with string_view
void do_it_with_string_view( void )
{
std::string a { "12345" };
for ( std::string_view v { a }; v.size() - 1; v.remove_prefix( 1 ) )
std::cout << v.substr( 0, 2 ) << " ";
std::cout << std::endl;
}
The string constructor can be used to get a copy of a substring.
string(const string& str, size_t pos, size_t n)
For example...
b = string(a, i, 2); // substring of a from position i, including 2 characters
This differs from substr in that the length n cannot be omitted. I offer this only as an alternative, not as an improvement.