I have arrays which contains either 1 or 0. I would like to append it and become one line string. At the moment I had failed doing so. here is my code. Please help because I could not manage to complete it. Everytime I load the final result to the console, only smiley faces and not 1 or 0. Please help
int pixelValueArray[256];
String testing;
for(int d=0;d<256;d++)
{
testing.append(1,pixelValueArray[d]);
}
cout<<testing;
Std provides the function std::to_string() (since c++11) to convert Datatypes like int to std::string: http://en.cppreference.com/w/cpp/string/basic_string/to_string .
Maybe this can help you.
The ASCII values for integer digits are given by '0' + digit.
for(int i = 0; i < 256; i++)
testing.append(1, '0' + pixelValueArray[i]);
Or you could use the simpler +=
for(int i = 0; i < 256; i++)
testing += '0' + pixelValueArray[i];
Related
The code below returns a reversed string. For example, it take input "codebyte" and returns "etybedoc".
string FirstReverse(string str) {
for(int i = 0, j = str.length() - 1; i < str.length() / 2; i++, j--)
{
str[i]^=str[j]^=str[i]^=str[j];
}
return str;
}
I am lost as to how this function works:
Why is the ^=-operator being used? It is a bitwise operator but why is it being used here?
Why is str.length() divided by 2 in the for loop?
What is with the alteration of str[i] and str[j]?
I want to work though it with values but I don't know where to begin. The introductory textbook I used did not cover this.
As an answer:
It's a swapping functionality similar to the famous bit-twiddling hacks.
A detailed explanation of this swapping mechanism can be found here.
The length is divided by two because otherwise you would undo every swap and end up with the original string again.
The indices i and j run against each other (from the beginning or end, respectively).
I have the following .txt file:
{{1,2,3,0}, {1,1,1,2}, {0,−1,3,9}}
This is a 3x4 matrix. I'm using strtok to extract the numbers and saving on a float matrix. The problem is, when p gets -1, it's being converted to zero when saved on matrix. How could I fix it?
p = strtok(&matrix[0u], " {},");
for (i = 0; i < m + 1; i++){
for (j = 0; j < n + 1; j++) {
aux[i][j] = atoi(p);
if (p)
p = strtok(NULL, " {},");
}
}
Is there a better way to extract the numbers, one at a time? How?
Your minus sign doesn't work. Compare:
this - is the ASCII minus sign
this − is your character whixh might be called "minus sign" by Unicode, but it is not normally recognised as such by C++ library functions
Don't copy code from Word documents and like places. If in doubt, convert to ASCII with iconv or a similar utility.
I'm working on an assignment where we have to create a "MyInt" class that can handle larger numbers than regular ints. We only have to handle non-negative numbers. I need to overload the >> operator for this class, but I'm struggling to do that.
I'm not allowed to #include <string>.
Is there a way to:
a. Accept input as a C-style string
b. Parse through it and check for white space and non-numbers (i.e. if the prompt is cin >> x >> y >> ch, and the user enters 1000 934H, to accept that input as two MyInts and then a char).
I'm assuming it has something to do with peek() and get(), but I'm having trouble figuring out where they come in.
I'd rather not know exactly how to do it! Just point me in the right direction.
Here's my constructor, so you can get an idea for what the class is (I also have a conversion constructor for const char *.
MyInt::MyInt (int n)
{
maxsize = 1;
for (int i = n; i > 9; i /= 10) {
// Divides the number by 10 to find the number of times it is divisible; that is the length
maxsize++;
}
intstring = new int[maxsize];
for (int j = (maxsize - 1); j >= 0; j--) {
// Copies the integer into an integer array by use of the modulus operator
intstring[j] = n % 10;
n = n / 10;
}
}
Thanks! Sorry if this question is vague, I'm still new to this. Let me know if I can provide any more info to make the question clearer.
So what you basically want is to parse a const char* to retrieve a integer number inside it, and ignore all whitespace(+others?) characters.
Remember that characters like '1' or 'M' or even ' ' are just integers, mapped to the ASCII table. So you can easily convert a character from its notation human-readable ('a') to its value in memory. There are plenty of sources on ascii table and chars in C/C++ so i'll let you find it, but you should get the idea. In C/C++, characters are numbers (of type char).
With this, you then know you can perform operations on them, like addition, or comparison.
Last thing when dealing with C-strings : they are null-terminated, meaning that the character '\0' is placed right after their last used character.
I am trying to convert integer into character. I know how to convert character to integer like this int(a) where a is a character. But when I am trying to convert integer to character, it is giving me a symbolic value. Please help me out.
I am doing something like below. Thanks in advance.
int a=0;
char str1[20];
for(int i=0;i<size;i++)
//somecalculation that sets value in a everytime and stores in str1
str1[i]=char(a)-'A'
Well I am running for loop and setting values in str1. This is just little of my code.
You could use str1[i] = static_cast<char>(a + '0');. This will convert a = 0 to '0', a = 1 to '1' etc. Consider the behaviour as undefined outside the range 0, ..., 9.
just use sprintf:
for(int i=0;i<size;i++)
//somecalculation that sets value in a everytime and stores in str1
sprintf(str1 + i, "%i", a);
since you noted that a is each time only a one digit integer, this should work, but this is not very error prone... normally you should check on how much digits were written:
for(int i=0;i<size;i++)
//somecalculation that sets value in a everytime and stores in str1
if (sprintf(str1 + i, "%i", a) != 1)
printf("expected to print only one character!\n");
PROBLEM SOLVED: thanks everyone!
I am almost entirely new to C++ so I apologise in advance if the question seems trivial.
I am trying to convert a string of letters to a set of 2 digit numbers where a = 10, b = 11, ..., Y = 34, Z = 35 so that (for example) "abc def" goes to "101112131415". How would I go about doing this? Any help would really be appreciated. Also, I don't mind whether capitalization results in the same number or a different number. Thank you very much in advance. I probably won't need it for a few days but if anyone is feeling particularly nice how would I go about reversing this process? i.e. "101112131415" --> "abcdef" Thanks.
EDIT: This isn't homework, I'm entirely self taught. I have completed this project before in a different language and decided to try C++ to compare the differences and try to learn C++ in the process :)
EDIT: I have roughly what I want, I just need a little bit of help converting this so that it applies to strings, thanks guys.
#include <iostream>
#include <sstream>
#include <string>
int returnVal (char x)
{
return (int) x - 87;
}
int main()
{
char x = 'g';
std::cout << returnVal(x);
}
A portable method is to use a table lookup:
const unsigned int letter_to_value[] =
{10, 11, 12, /*...*/, 35};
// ...
letter = toupper(letter);
const unsigned int index = letter - 'A';
value = letter_to_value[index];
cout << index;
Each character has it's ASCII values. Try converting your characters into ASCII and then manipulate the difference.
Example:
int x = 'a';
cout << x;
will print 97; and
int x = 'a';
cout << x - 87;
will print 10.
Hence, you could write a function like this:
int returnVal(char x)
{
return (int)x - 87;
}
to get the required output.
And your main program could look like:
int main()
{
string s = "abcdef"
for (unsigned int i = 0; i < s.length(); i++)
{
cout << returnVal(s[i]);
}
return 0;
}
This is a simple way to do it, if not messy.
map<char, int> vals; // maps a character to an integer
int g = 1; // if a needs to be 10 then set g = 10
string alphabet = "abcdefghijklmnopqrstuvwxyz";
for(char c : alphabet) { // kooky krazy for loop
vals[c] = g;
g++;
}
What Daniel said, try it out for yourself.
As a starting point though, casting:
int i = (int)string[0] + offset;
will get you your number from character, and: stringstream will be useful too.
How would I go about doing this?
By trying to do something first, and looking for help only if you feel you cannot advance.
That being said, the most obvious solution that comes to mind is based on the fact that characters (i.e. 'a', 'G') are really numbers. Suppose you have the following:
char c = 'a';
You can get the number associated with c by doing:
int n = static_cast<int>(c);
Then, add some offset to 'n':
n += 10;
...and cast it back to a char:
c = static_cast<char>(n);
Note: The above assumes that characters are consecutive, i.e. the number corresponding to 'a' is equal to the one corresponding to 'z' minus the amount of letters between the two. This usually holds, though.
This can work
int Number = 123; // number to be converted to a string
string Result; // string which will contain the result
ostringstream convert; // stream used for the conversion
convert << Number; // insert the textual representation of 'Number' in the characters in the stream
Result = convert.str(); // set 'Result' to the contents of the stream
you should add this headers
#include <sstream>
#include <string>
Many answers will tell you that characters are encoded in ASCII and that you can convert a letter to an index by subtracting 'a'.
This is not proper C++. It is acceptable when your program requirements include a specification that ASCII is in use. However, the C++ standard alone does not require this. There are C++ implementations with other character sets.
In the absence of knowledge that ASCII is in use, you can use translation tables:
#include <limits.h>
// Define a table to translate from characters to desired codes:
static unsigned int Translate[UCHAR_MAX] =
{
['a'] = 10,
['b'] = 11,
…
};
Then you may translate characters to numbers by looking them up in the table:
unsigned char x = something;
int result = Translate[x];
Once you have the translation, you could print it as two digits using printf("%02d", result);.
Translating in the other direction requires reading two characters, converting them to a number (interpreting them as decimal), and performing a similar translation. You might have a different translation table set up for this reverse translation.
Just do this !
(s[i] - 'A' + 1)
Basically we are converting a char to number by subtracting it by A and then adding 1 to match the number and letters