I got a string, that inside it has:
2@0.88315@1@1.5005@true@0.112 and it keep going…
I need to switch every number thats 2 or bigger, to 1,
so I wrote this :
for (i = 0 ; i < strlen(data) ; i++)
{
if (data[i] >= 50 && data[i] <= 57) // If it's a number
{
data[i] = '1'; // switch it to one
while (data[i] >= 48 && data[i] <= 57)
{
i++;
}
}
}
The problem is, that it makes numbers like 0.051511 as 1.111111 too…
Because it doesnt look at a double as one number, but every number seperatly…
How can I do it ?
Thanks
To clarify the question since it is unclear, you want to have the following input:
To be modified to be the following:
Your problem is that you need to parse each number into a float value to do any sort of comparison. Either this, or you will need to manually parse it by checking for a ‘.’ character. Doing it manually is rigid, error-prone and unnecessary because the C standard library provides functions which can help you.
Since this is homework, I’ll give you some tips on how to approach this problem instead of the actual solution. What you should do is try to write a solution with these steps and if you get stuck, edit the original question with the code you wrote, where it is failing and why you think it is failing.
Your first step is to tokenise the input into the following:
This can be done by iterating through the string and either splitting it or using the pointer after which a ‘@’ character occurs. Splitting the string can be done with
strtok. However,strtokwill split the string by modifying it which is not necessarily needed in our case. The simpler method is simply to iterate through the string and stop each time after a ‘@’ character is reached. The input would then be tokenised to the following:Some of these substrings do not start with a string which represents a float. You will need to determine which of them do. To do this, you can attempt to parse the front of each string as a float. This can be done with
sscanf. After parsing the floats, you will be able to do the comparison you want to.You are trying to modify the string into a different length so when replacing a float value by a ‘1’, you need to check the length of the original value. If it is longer than 1 character, you will have to shift the subsequent characters forward. For example:
If you parsed the first token and found it to be
> 2, you would replace the first character with a ‘1’. This result in:You then still need to delete the rest of that token by shifting the rest of the string down to get: