I'm working on this code that iterates over a string--that is actually a string representing an integer in this case--and fills an array with each "digit" of the string. So string "350" would result in an array with elements {3,5,0}.
Here is the code:
#include <stdlib.h>
#include <iostream>
using namespace std;
int main() {
int arr[5];
string test = "10000";
for(unsigned int i = 0; i<test.length(); i++) {
char c = test[i];
cout << c << endl;
arr[i] = c;
}
//printing the array for testing
for (int i = 5 - 1; i >= 0; i--)
cout << arr[i];
return 0;
}
char c = test[i];
arr[i] = c;
}
return 0;
}
The issue is that array that results from this is {49,48,48,48,48}. I have no idea why its doing that and where I have gone wrong with the code. Why is it adding the numbers 49 and 48, and how can I fix this?
Also if it helps anyone, here is a link to a stepper running through the code:
http://pythontutor.com/visualize.html#code=%0A%23include%20%3Cstdlib.h%3E%0A%23include%20%3Ciostream%3E%0A%0A%0Ausing%20namespace%20std%3B%0A%0A%0A%0Aint%20main%28%29%20%7B%0A%20%20int%20arr%5B5%5D%3B%0A%09string%20test%20%3D%20%2210000%22%3B%0A%20%20for%28unsigned%20int%20i%20%3D%200%3B%20i%3Ctest.length%28%29%3B%20i%2B%2B%29%20%7B%0A%20%20%20%20char%20c%20%3D%20test%5Bi%5D%3B%20//this%20is%20your%20character%0A%20%20%20%20arr%5Bi%5D%20%3D%20c%3B%0A%7D%0A%09return%200%3B%0A%7D%0A%0A%0A&cumulative=false&curInstr=19&heapPrimitives=false&mode=display&origin=opt-frontend.js&py=cpp&rawInputLstJSON=%5B%5D&textReferences=false
What you see in your array are the ascii for the characters your insert.
Here is what you should do to convert your character to an integer:
arr[i] = atoi(&c);
The 48 and 49 are your 0 and 1 in ascii. You need to convert from ascii to digits.
You created arr as an array of integers, thus by assigning character elements to it you implicitly cast them to an integer. When you do this, the ASCII value of the characters is printed, instead of the characters themselves. You should use an array of characters instead.
char arr[5];
Related
I am working on a system in which we have to create an array and store distinct numbers that can be obtained from an integer. Give Input:-
12
and the array of distinct numbers that can be generated from this number is:-
x={1,2,12}
But there is a catch that the distinct numbers cannot contain any leading zeros. I can delete a digit of the given number such that resulting number doesn't have any leading zeros.
Given Input
102
Now, the array formed is
x={0,1,2,10,12}
I am not able to solve the problem with leading zeros. Can anyone help me with the problem?
I solved this problem via substring. I computed the substring through 2 loops and if that string's first index value is zero, I didn't add it into my output array.
#include<iostream>
#include<string>
#include<sstream>
using namespace std;
int main() {
int num;
cin >> num;
vector<int> output;
string snum = to_string(num); //converting my input number into a string
//computing substring
for (int i = 0; i < snum.length(); i++) {
for (int j = i; j < snum.length(); j++) {
//substring method
string temp = snum.substr(i, j);
//if the first index is zero I continue my loop (leading zero)
if (temp[0] == '0')
continue;
else
{
//converting the string again into a number and add it to my output array
stringstream str(temp);
int n = 0;
str >> n;
output.push_back(n);
}
}
}
output.push_back(num);
//cout << output[0] << endl;
for (int i = 1; i < output.size(); i++)
cout << output[i] << "\n";
}
There maybe other optimized way to solve this problem.
I have 20 digit strings ex: 12345678912345678912.
I want to turn this into an array of ints [1,2,3...2]
How would I do that?
(I kept getting errors with sstream, atoi/stoi)
Create a new array, and convert each number character to number. Just subtract '0' from the number character and you will get the number.
The number character - '0' = the ASCII value of that character - the ASCII value of '0' = the number.
std::vector<int> digits;
for (int i = 0; i < s.size(); i++)
digits.push_back(s[i] - '0');
Using ASCII is way to here.
#include <iostream>
#include <cstring>
using namespace std;
int main() {
string s;
cin>>s;
int len = s.length();
int arr[len];
for( int it=0; it<len; it++ ){
// using ascii value
arr[it] = s[it] - '0';
}
for(int it=0; it<len; it++){
cout<<arr[it]<<" ";
}
return 0;
}
// Example program
#include <iostream>
#include <string>
int main()
{
// convert char to int
std::string str = "12345678912345678912";
int digits[str.size()];
for (size_t i=0; i<str.size(); i++) {
digits[i] = str[i] - '0';
}
// print out the string
std::cout << str << std::endl;
// print out the digits
for (size_t i=0; i<str.size(); i++) {
std::cout << digits[i];
}
std::cout << std::endl;
}
You need to learn to work with C++ standard string and character strings. Then learn to use standard function to convert character to integer. Following are some useful references:
http://www.cplusplus.com/reference/string/string/c_str/
http://www.cplusplus.com/reference/cstdlib/atoi/
http://www.cplusplus.com/reference/cstring/strncpy/
Above mentioned solutions are correct. Here is another way to solve your problem.
int main()
{
string input = "123456789";
int sum = 0;
const char * icstring = input.c_str(); // input character string
for(int i = 0; i < input.size(); i++)
{
char scstring[2]; // single character string
// Copy first digit to scstring
strncpy_s(scstring, icstring, 1);
// Convert scstring to integer using C library function 'atoi'
int digit = atoi(scstring); // cout << "i = " << endl;
sum += digit;
icstring++; // process next character
}
cout << "Sum of integers : " << sum << endl;
return 0;
}
I wrote the following code to convert string of type 'aaadddbbbccc' to 'a3d3b3c3' :
#include <iostream>
#include <string.h>
using namespace std;
void stringCompression(char *str,char *newStr){
int a[256] = {0};
int newCount = 0;
for(int i = 0; i < strlen(str) ; i++){
int j = str[i];
if (a[j] == 0 && strlen(newStr) <= strlen(str)){
a[j] = 1 ;
newStr[newCount] = str[i];
newCount++;
int count = 0;
for (int n = i; n < strlen(str); n++){
if(str[i] == str[n]){
count = count + 1;
}
}
newStr[newCount] =(char) count;
newCount++ ;
} else if (strlen(newStr) > strlen(str)){
strcpy(newStr,str);
}
}
}
int main() {
char str[] = "abcdabcdabcd";
char *newStr = new char[strlen(str)+1];
stringCompression(str,newStr);
cout << newStr;
return 0;
}
My problem is at step
newStr[newCount] =(char) count;
even though it is inserted but the output is not a3b3c3d3 but a*squarebox*b*squarebox*c*squarebox*d*squarebox*. squarebox being 2*2 matrix with one value as the number that is desired. I am using eclipse IDE.
. I would really appreciate your help. How can I correct this. Am I using the correct approach?
Thanks in advance.
The problem is that
newStr[newCount] =(char) count;
converts the number "count" into the character corresponding to that number according to the ascii table (http://www.asciitable.com/), which is "end of text" for "3", that does not correspond to any number.
You should convert "count" into a string instead. See here for example:
Easiest way to convert int to string in C++
However, be aware that it might be longer than one digit, for example if count is "11", it will take two letters in string representation.
Hey you have to use http://www.cplusplus.com/reference/cstdlib/itoa/ to convert integer to char string
I'm writing an encryption program for class. I need to be able to track the position of spaces in a string, as well as adding 13 to the ASCII value of each character of the string. I keep getting an error in line 46, and I don't see what I'm doing wrong.
/*
program 4
use an array to store the string
convert decimal values to ASCII, add 13 to the ASCII values,
convert back to decimal
the character for the space shoud be determined by the character
that came before it.
The character before it should have 4 added to it and
placed after itself to act as the space.
*/
#include <iostream>
#include <fstream>
#include <string>
#include <conio.h>
using namespace std;
int valueChange(string array), length(string array);
int spacePosition[0];
string message[0], encrypt[0];
int main()
{
cout << "Please enter your message."; //start with this
cin >> message[0];
int value = length(message[0]);
int count=0;
/*
store message as an array
loop through array, adding 13 to each value, use tolower() on each value
if value is
*/
for (int i=0; i < value; i++)
{
valueChange(message[i]);
if (message[i] == ' ') //checks for spaces in the string
{
spacePosition[count] = i + 1; //records the placement of spaces
//in the string
//have the array cast the i value to a new int value
//store space positions in an array
count++;
}
}
cout << "&";
cout << "Message encrypted and transmitted."; //final message
getch();
return 0;
}
int valueChange(int array[])
{
array[0] += 13;
if (array[0] > 122)
{
array[0] - 122;
}
return (array[0]);
}
int length(string array)
{
return (array.length() - 1);
}
If you need to search for spaces you can use string::find_first_of(string). You just need to write
`
std::string yourstring;
yourstring.find_first_of(" ");
`
then you need to iterate through the whole string using iterator.
And why are you declearing array if zero length? You can simply use simple std::string class. If you are not allowed to then simply use find_first_of(....) function available in standerd library. It basically returns the iterator to the first matching element.
int spacePosition[0];
string message[0], encrypt[0];
Probably want those to be 1's... or not use an array at all. But you are declaring arrays with 0 length, so yeah, you're going to segfault when you try writing to them.
I am looking to pass the int values of an array to the indices of a string array "behind the scenes." I want the string arrays to be ouput with their strings, however I want to do math on the indices the strings represent.
In other words I would like to combine or blend them together so that I have 4 arrays: 2 of them are int arrays, 1 of the int arrays is for doing math on; and 2 of them are string arrays, both of them are for display to the screen purposes only.
If I try to loop through the int arrays and assign the string array elements to their corresponding indices, it won't compile, and I get the error message:
"Cannot convert 'std::string' to 'int' in assignment."
If I try to loop through the string arrays and assign them the int array values to their corresponding indices, it compiles, however I get the ASCII representation of the int values, rather than the numbers.
Here is the code for looping through the int arrays:
#include <iostream>
using namespace std;
int main()
{
int typeArray[4] = {55,66,77,88};
int valArray[13] = {1,2,3,4,5,6,7,8,9,10,11,12,13};
string types[4] = {"Manny", "Moe", "Jack", "John" };
string values[13] = {"One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten",
"Eleven","Twelve","Thirteen"};
for (int i = 0; i < sizeof(typeArray)/sizeof(int); i++)
{
for (int j = 0; j < sizeof(valArray)/sizeof(int); j++)
{
typeArray[i] = types[0];
valArray[j] = values[0];
}
}
system("Pause");
return 0;
}
AGAIN, IT WON'T COMPILE, AND I GET THE ERROR MESSAGE NOTED ABOVE.
Here is the code for looping through the string arrays and the output:
#include <iostream>
using namespace std;
int main()
{
int typeArray[4] = {55,66,77,88};
int valArray[13] = {1,2,3,4,5,6,7,8,9,10,11,12,13};
string types[4] = {"Manny", "Moe", "Jack", "John" };
string values[13] = {"One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten",
"Eleven","Twelve","Thirteen"};
for (int i = 0; i < sizeof(types)/sizeof(int); i++)
{
for (int j = 0; j < sizeof(values)/sizeof(int); j++)
{
types[i] = typeArray[0];
values[j] = valArray[0];
cout << "This is types array: " << types[i] << " This is values array: " << values[j] << endl;
}
}
system("Pause");
return 0;
}
HERE IS THE OUTPUT SHOWING ASCII CONVERSIONS OF THE INTS:
This is types array: 7 This is values array: ☺
Please advise, thanks!
The problem is you can't store a String in an int you can however create a String from an int this is why the second option compiles.
However when you do this you get the character with the ASCII value equal to the int. So in your case you get the ASCII character for 7 which is the character you are printing.
If you want to print the 7 you need to get the ASCII code for 7 you can do this with:
types[i] = typeArray[0] + '0';
But I don't think this what you actually want to do.
You could create a structure that holds an int and a String to keep them together, and then make an array of that struct.
typedef struct typeStruct {
int value;
string disp;
} typeStruct;
typeStruct types[13];
Edit: based on your comment on this answer I think you want this
string values[6] = {"INVALID", "one", "two", "three", "four", "five"};
int size = 6;
...
//This prints the value for a given int
void printValue(int val) {
cout << values[val] << endl;
}
//This gets the int val for a given string
int getValue(string str) {
for(int i = 0; i < size; i++) {
if(str.compare(values[i]) == 0) {
return i;
}
}
return -1;
}
It looks like you should use
Map<int, string>
It will help you to bind an integer value to the string.
Anyway, you're getting an error because you are trying to assign string to int.