C/C++ - "Negative" string converted to zero - c++

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.

Related

Print out each character randomly

I am creating a small game where the user will have hints(Characters of a string) to guess the word of a string. I have the code to see each individual character of the string, but is it possible that I can see those characters printed out randomly?
string str("TEST");
for (int i = 0; i < str.size(); i++){
cout <<" "<< str[i];
output:T E S T
desired sample output: E T S T
Use random_shuffle on the string:
random_shuffle(str.begin(), str.end());
Edits:
C++11 onwards use:
auto engine = std::default_random_engine{};
shuffle ( begin(str), end(str), engine );
Use the following code to generate the letters randomly.
const int stl = str.size();
int stl2 = stl;
while (stl2 >= 0)
{
int r = rand() % stl;
if (str[r] != '0')
{
cout<<" "<<str[r];
str[r] = '0';
stl2--;
}
}
This code basically generates the random number based on the size of the String and then prints the character placed at that particular position of the string.
To avoid the reprinting of already printed character, I have converted the character printed to "0", so next time same position number is generated, it will check if the character is "0" or not.
If you need to preserve the original string, then you may copy the string to another variable and use it in the code.
Note: It is assumed that string will contain only alphabetic characters and so to prevent repetition, "0" is used. If your string may contain numbers, you may use a different character for comparison purpose

Rounding down/truncating double

I'm doing calculations with financial data formatted as follows:
<up to 5 digits>.<two digits>
Basically, in my program I'm encountering a floating point error. For example, if I have:
11.09 - (11.09 * 0.005) = 11.03455
I want to be able to use 11.03455 and not what's generated: 11.0345499999999...
I'm comparing values that my program generates with values I have in text files that are in string format. I only need two decimal points of precision and I can round down. Is there a way that I can cut this to 11.03?
I was thinking it would be easiest if I turn this into a string and just parse it character by character, only adding two characters past the '.' character. Is this a good solution? Any better ideas?
Here is what I have:
string dataProcessor::createTwoDec(double price){
string s = to_string(price);
string output = "";
int dist = 0;
int num_wanted = 0;
bool pt_found = false;
for(int i = 0; i < s.length(); i++){
if(s[i] == '.')
pt_found = true;
if(pt_found)
dist++;
if(dist > 3)
break;
output += s[i];
num_wanted++;
}
return output.substr(0, num_wanted);
}
You can use the following formula for round-off by n decimal places (n is not too large):
round(x*10^n)/10^n
where n is number of decimal places required.
In your case, n is 5. Hence, it will be
result = round(result*100000)/100000;
See How do you round off decimal places in C++?

How to convert data in array to string c++

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];

C++ - Overloading operator>> and processing input using C-style strings

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.

Solving "Welcome to Code Jam" from Google Code Jam 2009

I am trying to solve the following code jam question,ive made some progress but for few cases my code give wrong outputs..
Welcome to Code jam
So i stumbled on a solution by dev "rem" from russia.
I've no idea how his/her solution is working correctly.. the code...
const string target = "welcome to code jam";
char buf[1<<20];
int main() {
freopen("input.txt", "rt", stdin);
freopen("output.txt", "wt", stdout);
gets(buf);
FOR(test, 1, atoi(buf)) {
gets(buf);
string s(buf);
int n = size(s);
int k = size(target);
vector<vector<int> > dp(n+1, vector<int>(k+1));
dp[0][0] = 1;
const int mod = 10000;
assert(k == 19);
REP(i, n) REP(j, k+1) {// Whats happening here
dp[i+1][j] = (dp[i+1][j]+dp[i][j])%mod;
if (j < k && s[i] == target[j])
dp[i+1][j+1] = (dp[i+1][j+1]+dp[i][j])%mod;
}
printf("Case #%d: %04d\n", test, dp[n][k]);
}
exit(0);
}//credit rem
Can somebody explain whats happening in the two loops?
Thanks.
What he is doing: dynamic programming, this far you can see too.
He has 2D array and you need to understand what is its semantics.
The fact is that dp[i][j] counts the number of ways he can get a subsequence of the first j letters of welcome to code jam using all the letters in the input string upto the ith index. Both indexes are 1 -based to allow for the case of not taking any letters from the strings.
For example if the input is:
welcome to code jjam
The values of dp in different situations are going to be:
dp[1][1] = 1; // first letter is w. perfect just the goal
dp[1][2] = 0; // no way to have two letters in just one-letter string
dp[2][2] = 1; // again: perfect
dp[1][2] = 1; // here we ignore the e. We just need the w.
dp[7][2] = 2; // two ways to construct we: [we]lcome and [w]elcom[e].
The loop you are specifically asking about calculates new dynamic values based on the already calculated ones.
Whoa, I was practicing this problem few days ago and and stumbled across this question.
I suspect that saying "he's doing dynamic programming" won't not explain too much if you did not study DP.
I can give clearer implementation and easier explanation:
string phrase = "welcome to code jam"; // S
string text; getline(cin, text); // T
vector<int> ob(text.size(), 1);
int ans = 0;
for (int p = 0; p < phrase.size(); ++p) {
ans = 0;
for (int i = 0; i < text.size(); ++i) {
if (text[i] == phrase[p]) ans = (ans + ob[i]) % 10000;
ob[i] = ans;
}
}
cout << setfill('0') << setw(4) << ans << endl;
To solve the problem if S had only one character S[0] we could just count number of its occurrences.
If it had only two characters S[0..1] we see that each occurrence T[i]==S[1] increases answer by the number of occurrences of S[0] before index i.
For three characters S[0..2] each occurrence T[i]==S[2] similarly increases answer by number of occurrences of S[0..1] before index i. This number is the same as the answer value at the moment the previous paragraph had processed T[i].
If there were four characters, the answer would be increasing by number of occurrences of the previous three before each index at which fourth character is found, and so on.
As every other step uses values from the previous ones, this can be solved incrementally. On each step p we need to know number of occurrences of previous substring S[0..p-1] before any index i, which can be kept in array of integers ob of the same length as T. Then the answer goes up by ob[i] whenever we encounter S[p] at i. And to prepare ob for the next step, we also update each ob[i] to be the number of occurrences of S[0..p] instead — i.e. to the current answer value.
By the end the latest answer value (and the last element of ob) contain the number of occurrences of whole S in whole T, and that is the final answer.
Notice that it starts with ob filled with ones. The first step is different from the rest; but counting number of occurrences of S[0] means increasing answer by 1 on each occurrence, which is what all other steps do, except that they increase by ob[i]. So when every ob[i] is initially 1, the first step will run just like all others, using the same code.