Roman Numeral To Decimal - c

Trying to implement a very simple Roman Numeral to Decimal converter but can't seem to figure out a way for the program to return -1 if any non-roman numeral characters are in the string. This is what I have so far.
#include <stdio.h>
#include <ctype.h>
int convertFromRoman(const char *s)
{
int i = 0;
int total = 0;
while (s[i] != '\0') {
if (isalpha(s[i]) == 0) {
return -1;
}
if (toupper(s[i]) == 'I') {
total += 1;
}
if (toupper(s[i]) == 'V') {
total += 5;
}
if (toupper(s[i]) == 'X') {
total += 10;
}
if (toupper(s[i]) == 'L') {
total += 50;
}
if (toupper(s[i]) == 'C') {
total += 100;
}
if (toupper(s[i]) == 'D') {
total += 500;
}
if (toupper(s[i]) == 'M') {
total += 1000;
} else {
return -1;
}
i++;
}
if (total == 0) {
return -1;
}
return total;
}
int main()
{
printf("%d\n", convertFromRoman("XVII"));
printf("%d\n", convertFromRoman("ABC"));
}
The first one should return 17 and the second one should return -1. However they both return -1 but if I remove the else statement, the first one returns 17 and the second one returns 100.
Any help is appreciated.

Change if() if() if() else to if() else if () else if() else
if (toupper(s[i]) == 'I') {
total += 1;
}
else if (toupper(s[i]) == 'V') {
total += 5;
}
else if (toupper(s[i]) == 'X') {
total += 10;
}
....
else if (toupper(s[i]) == 'M') {
total += 1000;
} else {
return -1;
}

Not really an answer, just a bit of fun/alternate way of looking at the problem. It does solve the problem if you're not considering ordering just adding "digit" values.
char *romanNumerals = "IVXLCDM";
int values[] = { 1, 5, 10, 50, 100, 500, 1000 };
int convertFromRoman(const char *s) {
int val = 0;
for (int i = 0; s[i]; i++) {
char *idx;
if (NULL == (idx = strchr(romanNumerals, toupper(s[i])))) {
return -1;
}
val += values[idx - romanNumerals];
}
return val;
}

Related

Error in solution to a problem of matrix of "o's" and "x's" in C language. In this we need to count and identify adjacent elements

Given a n × n checkerboard. Each cell of the board has either character 'x', or character 'o'. Is it true that each cell of the board has even number of adjacent cells with 'o'? Two cells of the board are adjacent if they share a side.
Input
The first line contains an integer n (1 ≤ n ≤ 100). Then n lines follow containing the description of the checkerboard. Each of them contains n characters (either 'x' or 'o') without spaces.
Output
Print "YES" or "NO" (without the quotes) depending on the answer to the problem.
I have been pondering quite a while as to what I have done wrong, can someone please help me point out the error in my logic in my code.
#include<stdio.h>
int main () {
int n,flag=0;
scanf("%d",&n);
char arr[n][n];
int arr_counter[n][n];
for (int x=0;x<n;x++) {
for (int y=0;y<n;y++) {
arr_counter[x][y] = 0;
}
}
for (int i=0;i<n;i++) {
for (int j=0;j<n;j++) {
scanf("%c",&arr[i][j]);
}
}
// corners
// top left
if(arr[1][0]=='o') {
arr_counter[0][0] += 1;
}
if(arr[0][1] == 'o') {
arr_counter[0][0] += 1;
}
// top right
if(arr[0][n-2]=='o') {
arr_counter[0][n-1] += 1;
}
if(arr[1][n-1] == 'o') {
arr_counter[0][n-1] += 1;
}
// bottom left
if(arr[n-2][0]=='o') {
arr_counter[n-1][0] += 1;
}
if(arr[n-1][1] == 'o') {
arr_counter[n-1][0] += 1;
}
// bottom right
if(arr[n-2][n-1]=='o') {
arr_counter[n-1][n-1] += 1;
}
if(arr[n-1][n-2] == 'o') {
arr_counter[n-1][n-1] += 1;
}
// edges
for (int a=1;a<n;a++) {
if(arr[0][a+1] == 'o') {
arr_counter[0][a] += 1;
}
if(arr[0][a-1] == 'o') {
arr_counter[0][a] += 1;
}
if(arr[1][a] == 'o') {
arr_counter[0][a] += 1;
}
}
for (int b=1;b<n;b++) {
if(arr[b-1][0] == 'o') {
arr_counter[b][0] += 1;
}
if(arr[b+1][0] == 'o') {
arr_counter[b][0] += 1;
}
if(arr[b][1] == 'o') {
arr_counter[b][0] += 1;
}
}
for (int c=1;c<n;c++) {
if(arr[c-1][n-1] == 'o') {
arr_counter[c][n-1] += 1;
}
if(arr[c+1][n-1] == 'o') {
arr_counter[c][n-1] += 1;
}
if(arr[c][n-2] == 'o') {
arr_counter[c][n-1] += 1;
}
}
for (int d=1;d<n;d++) {
if(arr[n-1][d+1] == 'o') {
arr_counter[n-1][d] += 1;
}
if(arr[n-1][d-1] == 'o') {
arr_counter[n-1][d] += 1;
}
if(arr[n-2][d] == 'o') {
arr_counter[n-1][d] += 1;
}
}
//middle
for (int s=1;s<n-1;s++) {
for (int t=1;t<n-1;t++) {
if(arr[s+1][t] == 'o') {
arr_counter[s][t] += 1;
}
if(arr[s-1][t] == 'o') {
arr_counter[s][t] += 1;
}
if(arr[s][t+1] == 'o') {
arr_counter[s][t] += 1;
}
if(arr[s][t-1] == 'o') {
arr_counter[s][t] += 1;
}
}
}
for (int k=0;k<n;k++) {
for (int l=0;l<n;l++) {
if (arr_counter[k][l]%2 != 0) {
flag = 1;
}
}
}
if (flag == 0) {
printf("YES");
} else if (flag == 1) {
printf("NO");
}
}
/*
Test Case 1
input
3
xxo
xox
oxx
output
YES
Test Case 2
input
4
xxxo
xoxo
oxox
xxxx
output
NO
*/

C function doesn't return string, though it should

I'm super new in C, trying to solve CS50's credit problem here.
So I wrote a function, that should check some parameters, and return a string, which I use in the main function to print an answer.
#include <stdio.h>
#include <stdlib.h>
#include <cs50.h>
#include <math.h>
int lunh(long n);
char* check(long nu);
int main(void)
{
long number = get_long("Number: ");
printf("%s", check(number));
}
int lunh(long n)
{
int length, step_one, num;
long tens;
step_one = 0;
length = floor(log10(labs(n))) + 1;
for (int i = length, powering = 1; i > length / 2; i--)
{
tens = pow(10, powering);
num = ((n / tens) % 10) * 2;
if (floor(log10(abs(num))) + 1 > 1)
{
while (num)
{
step_one += num % 10;
num /= 10;
}
step_one += num;
powering += 2;
}
else
{
step_one += num;
powering += 2;
}
}
for (int i = length, powering = 0; i > length / 2; i--)
{
tens = pow(10, powering);
num = ((n / tens) % 10);
step_one += num;
powering += 2;
}
if (step_one % 10 == 0)
{
return 1;
}
else
{
return 0;
}
}
char* check(long nu)
{
int l, first_two_digits, first_one;
l = floor(log10(labs(nu))) + 1;
first_one = nu / 1000;
first_two_digits = nu / 100;
char* answer = NULL;
if (l == 15)
{
if (first_two_digits == 34 || first_two_digits == 37)
{
if (lunh(nu) == 1)
{
answer = "AMEX";
}
else
{
answer = "INVALID";
}
}
}
else if (l == 13 || first_one == 4)
{
if (lunh(nu) == 1)
{
answer = "VISA";
}
else
{
answer = "INVALID";
}
}
else if (l == 16)
{
if (first_two_digits == 51 || first_two_digits == 52 || first_two_digits == 53 || first_two_digits == 54 || first_two_digits == 55)
{
if (lunh(nu) == 1)
{
answer = "MASTERCARD";
}
else
{
answer = "INVALID";
}
}
}
else
{
answer = "INVALID";
}
printf("%s", answer);
return answer;
}
Input: 4003600000000014
Expected output: "VISA"
Current output: nothing, after inputting the number, the program stops.
At least one problem is here: else if (l == 13 || first_one == 4). From the spec:
Visa uses 13- and 16-digit numbers.
Visa numbers all start with 4
That if test will produce VISA if length is 13 or card starts with 4. The sample input is a 16 digit number.

condition where two dots is typed it should print no?

First time posting here, having a problem with this code.
I want it to print no when there is more than 1 dot, for instance '2..5'.
Tried to put the following if statement:
if(num[i] == '..'){
printf("no \n);}
however with no success.
Im new to programming!
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
char *num = argv[1];
if (num[0] == '+' && strlen(num) >= 2 || num[0] == '-' && strlen(num) >= 2 || num[0] == '.' || (num[0] >= '0' && num[0] <= '9'))
{
for (int i = 1; i < strlen(num); i++) {
if (!(num[i] == '.' || (num[i] >= '0' && num[i] <= '9')) ) {
printf("no \n");
}
}
printf("yes \n");
} else {
printf("no \n");
}
}
}
Use this:
if(!(strcmp(num[i], "..")))
instead of
if(num[i] == '..')
Parsing numbers is not trivial. But the following works:
double parsenum(const char *num)
{
unsigned int i=0;
int neg= 1;
double result= 0.0;
int nFraction=1;
while (num[i]=='-' || num[i]=='+') {
neg= neg * (num[i]=='-'? -1 : 1);
i++;
}
while (num[i]) {
if (num[i]>='0' && num[i]<= '9') {
if (nFraction==1) {
result= result * 10 + (num[i]-'0');
}
else {
result= result + ((double)(num[i]-'0') / nFraction);
nFraction *= 10;
}
i++;
}
else if (num[i]=='.')
{
if (nFraction>1) {
printf("%s: no\n", num);
return 0.0;
}
nFraction *= 10;
i++;
}
else
{
printf("%s: no\n", num);
return 0.0;
}
}
result *= neg;
return result;
}
Test inputs:
printf("%f\n",parsenum("2..5"));
printf("%f\n",parsenum("-2.5"));
printf("%f\n",parsenum("--2.5"));
printf("%f\n",parsenum("2.5.6"));
printf("%f\n",parsenum("++2.555"));
printf("%f\n",parsenum("255.555"));

Printing string pointers in c

So, essentially I have two files:
File 1:
//
// main.c
// frederickterry
//
// Created by Rick Terry on 1/15/15.
// Copyright (c) 2015 Rick Terry. All rights reserved.
//
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int size (char *g) {
int ofs = 0;
while (*(g+ofs) != '\0') {
++ofs;
}
return ofs;
}
int parse(char *g) {
// Setup
char binaryConnective;
int negated = 0;
// Looking for propositions
int fmlaLength = size(g);
if(fmlaLength == 0) {
return 1;
}
if(fmlaLength == 1) {
if(g[0] == 'p') {
return 1;
} else if (g[0] == 'q') {
return 1;
} else if (g[0] == 'r') {
return 1;
} else {
return 0;
}
}
// Now looking for negated preposition
if(fmlaLength == 2) {
char temp[100];
strcpy(temp, g);
if(g[0] == '-') {
negated = 1;
int negatedprop = parse(g+1);
if(negatedprop == 1) {
return 2;
}
}
}
// Checking if Binary Formula
char arrayleft[50];
char arrayright[50];
char *left = "";
char *right = "";
int numLeft = 0;
int numRight = 0;
int bclocation = 0;
int binarypresent = 0;
if(fmlaLength != 1 && fmlaLength != 2) {
if(g[0] == '-') {
int negatedBinary = parse(g+1);
if(negatedBinary == 1 || negatedBinary == 2 || negatedBinary == 3) {
return 2;
} else {
return 0;
}
}
int i = 0;
int l = 0;
int p = strlen(g);
for(l = 0; l < strlen(g)/2; l++) {
if(g[l] == '(' && g[p-l-1] == ')') {
i++;
}
}
for(int q = i; q < strlen(g); q++) {
if(g[q] == '(') {
numLeft++;
} else if(g[q] == ')') {
numRight++;
}
arrayleft[q] = g[q];
//printf("%c", arrayleft[i]);
//printf("%s", left);
if((numRight == numLeft) && (g[q+1] == 'v' || g[q+1] == '>' || g[q+1] == '^')) {
arrayleft[q+1] = '\0';
bclocation = q+1;
binaryConnective = g[q+1];
binarypresent = 1;
// printf("The binary connecive is: %c\n", binaryConnective);
break;
}
}
if(binarypresent == 0) {
return 0;
}
int j = 0;
for(int i = bclocation+1; i < strlen(g)-1; i++) {
arrayright[j] = g[i];
j++;
}
arrayright[j] = '\0';
left = &arrayleft[1];
right = &arrayright[0];
//printf("Printed a second time, fmla 1 is: %s", left);
int parseleft = parse(left);
// printf("Parse left result: %d\n", parseleft);
if(parseleft == 0) {
return 0;
}
int parseright = parse(right);
if(parseright == 0) {
return 0;
}
// printf("Parse right result: %d\n", parseleft);
if(negated == 1) {
return 2;
} else {
return 3;
}
}
return 0;
}
int type(char *g) {
if(parse(g) == 1 ||parse(g) == 2 || parse(g) == 3) {
if(parse(g) == 1) {
return 1;
}
/* Literals, Positive and Negative */
if(parse(g) == 2 && size(g) == 2) {
return 1;
}
/* Double Negations */
if(g[0] == '-' && g[1] == '-') {
return 4;
}
/* Alpha & Beta Formulas */
char binaryConnective;
int numLeft = 0;
int numRight = 0;
int bclocation = 0;
int binarypresent = 0;
int i = 0;
if(g[0] == '(') {
i++;
}
if(g[0] == '-') {
i++;
if(g[1] == '(') {
i++;
}
}
for(i; i < strlen(g); ++i) {
if(g[i] == '(') {
numLeft++;
} else if(g[i] == ')') {
numRight++;
}
if(numRight == numLeft) {
if(g[i+1] == 'v' || g[i+1] == '>' || g[i+1] == '^') {
bclocation = i+1;
binaryConnective = g[i+1];
binarypresent = 1;
break;
}
}
}
/* Connective established */
if(binaryConnective == '^') {
if(g[0] == '-') {
return 3;
} else {
return 2;
}
} else if(binaryConnective == '>') {
if(g[0] == '-') {
return 2;
} else {
return 3;
}
} else if (binaryConnective == 'v') {
if(g[0] == '-') {
return 2;
} else {
return 3;
}
}
}
return 0;
}
char bin(char *g) {
char binaryConnective;
char arrayLeft[50];
int numLeft = 0;
int numRight = 0;
int bclocation = 0;
int i = 0;
if(g[0] == '(') {
i++;
}
if(g[0] == '-') {
i++;
if(g[1] == '(') {
i++;
}
}
for(i; i < strlen(g); ++i) {
if(g[i] == '(') {
numLeft++;
} else if(g[i] == ')') {
numRight++;
}
int j = 0;
arrayLeft[j++] = g[i];
if(numRight == numLeft) {
if(g[i+1] == 'v' || g[i+1] == '>' || g[i+1] == '^') {
arrayLeft[i+1] = '\0';
bclocation = i+1;
binaryConnective = g[i+1];
return binaryConnective;
}
}
}
return binaryConnective;
}
char *partone(char *g) {
char binaryConnective;
char arrayLeft[50];
char arrayRight[50];
int numLeft = 0;
int numRight = 0;
int bclocation = 0;
int i = 0;
if(g[0] == '(') {
i++;
}
if(g[0] == '-') {
i++;
if(g[1] == '(') {
i++;
}
}
int j = 0;
for(i; i < strlen(g); ++i) {
if(g[i] == '(') {
numLeft++;
} else if(g[i] == ')') {
numRight++;
}
arrayLeft[j] = g[i];
if(numRight == numLeft) {
if(g[i+1] == 'v' || g[i+1] == '>' || g[i+1] == '^') {
arrayLeft[j+1] = '\0';
bclocation = i+1;
binaryConnective = g[i+1];
break;
}
}
j++;
}
int m = 0;
for(int k = bclocation+1; k < strlen(g)-1; k++) {
arrayRight[m] = g[k];
m++;
}
arrayRight[m] = '\0';
char* leftSide = &arrayLeft[0];
// printf("%s\n", leftSide);
// printf("%s\n", rightSide);
int k = 0;
k++;
return leftSide;
}
char *parttwo(char *g) {
char binaryConnective;
char arrayLeft[50];
char arrayRight[50];
int numLeft = 0;
int numRight = 0;
int bclocation = 0;
int i = 0;
if(g[0] == '(') {
i++;
}
if(g[0] == '-') {
i++;
if(g[1] == '(') {
i++;
}
}
int j = 0;
for(i; i < strlen(g); ++i) {
if(g[i] == '(') {
numLeft++;
} else if(g[i] == ')') {
numRight++;
}
arrayLeft[j] = g[i];
if(numRight == numLeft) {
if(g[i+1] == 'v' || g[i+1] == '>' || g[i+1] == '^') {
arrayLeft[j+1] = '\0';
bclocation = i+1;
binaryConnective = g[i+1];
break;
}
}
j++;
}
int m = 0;
int n = size(g) - 1;
if(g[strlen(g)-1] != ')') {
n++;
}
for(int k = bclocation+1; k < n; k++) {
arrayRight[m] = g[k];
m++;
}
arrayRight[m] = '\0';
char* leftSide = &arrayLeft[0];
char* rightSide = &arrayRight[0];
// printf("%s\n", leftSide);
// printf("%s\n", rightSide);
return rightSide;
}
char *firstexp(char *g) {
char* left = partone(g);
char leftArray[50];
int i = 0;
for(i; i < strlen(left); i++) {
leftArray[i] = left[i];
}
leftArray[i] = '\0';
char binConnective = bin(g);
int typeG = type(g);
if(typeG == 2) {
if(binConnective == '^') {
return &leftArray;
} else if(binConnective == '>') {
return &leftArray;
}
} else if(typeG == 3) {
if(binConnective == 'v')
return &leftArray;
}
char temp[50];
for(int i = 0; i < strlen(leftArray); i++) {
temp[i+1] = leftArray[i];
}
temp[0] = '-';
char* lefttwo = &temp[0];
if(typeG == 2) {
if(binConnective == 'v') {
return lefttwo;
}
} else if(typeG == 3) {
if(binConnective == '>' || binConnective == '^') {
return lefttwo;
}
}
return "Hello";
}
char *secondexp(char *g) {
// char binaryConnective = bin(g);
// char* right = parttwo(g);
// char rightArray[50];
// int i = 0;
// for(i; i< strlen(right); i++) {
// rightArray[i+1] = right[i];
// }
// rightArray[i] = '\0';
// int typeG = type(g);
// if(type(g) == 2) {
// if(binaryConnective == '^') {
// return &rightArray;
// }
// } else if(type(g) == 3) {
// if(binaryConnective == 'v' || binaryConnective == '>') {
// return &rightArray;
// }
// }
return "Hello";
}
typedef struct tableau tableau;
\
\
struct tableau {
char *root;
tableau *left;
tableau *right;
tableau *parent;
int closedbranch;
};
int closed(tableau *t) {
return 0;
}
void complete(tableau *t) {
}
/*int main(int argc, const char * argv[])
{
printf("Hello, World!\n");
printf("%d \n", parse("p^q"));
printf("%d \n", type("p^q"));
printf("%c \n", bin("p^q"));
printf("%s\n", partone("p^q"));
printf("%s\n", parttwo("p^q"));
printf("%s\n", firstexp("p^q"));
printf("Simulation complete");
return 0;
}*/
File 2:
#include <stdio.h>
#include <string.h> /* for all the new-fangled string functions */
#include <stdlib.h> /* malloc, free, rand */
#include "yourfile.h"
int Fsize = 50;
int main()
{ /*input a string and check if its a propositional formula */
char *name = malloc(Fsize);
printf("Enter a formula:");
scanf("%s", name);
int p=parse(name);
switch(p)
{case(0): printf("not a formula");break;
case(1): printf("a proposition");break;
case(2): printf("a negated formula");break;
case(3): printf("a binary formula");break;
default: printf("what the f***!");
}
printf("\n");
if (p==3)
{
printf("the first part is %s and the second part is %s", partone(name), parttwo(name));
printf(" the binary connective is %c \n", bin(name));
}
int t =type(name);
switch(t)
{case(0):printf("I told you, not a formula");break;
case(1): printf("A literal");break;
case(2): printf("An alpha formula, ");break;
case(3): printf("A beta formula, ");break;
case(4): printf("Double negation");break;
default: printf("SOmewthing's wrong");
}
if(t==2) printf("first expansion fmla is %s, second expansion fmla is %s\n", firstexp(name), secondexp(name));
if(t==3) printf("first expansion fmla is %s, second expansion fmla is %s\n", firstexp(name), secondexp(name));
tableau tab;
tab.root = name;
tab.left=0;
tab.parent=0;
tab.right=0;
tab.closedbranch=0;
complete(&tab);/*expand the root node then recursively expand any child nodes */
if (closed(&tab)) printf("%s is not satisfiable", name);
else printf("%s is satisfiable", name);
return(0);
}
If you look at the first file, you'll see a method called * firstexp(char * g).
This method runs perfectly, but only if another method called * secondexp(char * g) is commented out.
If * secondexp(char * g) is commented out, then *firstexp runs like this:
Enter a formula:((pvq)>-p)
a binary formula
the first part is (pvq) and the second part is -p the binary connective is >
A beta formula, first expansion fmla is -(pvq), second expansion fmla is Hello
((pvq)>-p) is satisfiableProgram ended with exit code: 0
otherwise, if *secondexp is not commented out, it runs like this:
Enter a formula:((pvq)>-p)
a binary formula
the first part is (pvq) and the second part is -p the binary connective is >
A beta formula, first expansion fmla is \240L, second expansion fmla is (-
((pvq)>-p) is satisfiable. Program ended with exit code: 0
As you can see, the outputs are completely different despite the same input. Can someone explain what's going on here?
In the commented-out parts of secondexp and in parttwo, you return the address of a local variable, which you shouldn't do.
You seem to fill a lot of ad-hoc sized auxiliary arrays. These have the problem that they might overflow for larger expressions and also that you cannot return them unless you allocate them on the heap with malloc, which also means that you have to free them later.
At first glance, the strings you want to return are substrings or slices of the expression string. That means that the data for these strings is already there.
You could (safely) return pointers into that string. That is what, for example strchr and strstr do. If you are willing to modify the original string, you could also place null terminators '\0' after substrings. That's what strtok does, and it has the disadvantage that you lose the information at that place: If you string is a*b and you modify it to a\0b, you will not know which operator there was.
Another method is to create a struct that stores a slice as pointer into the string and a length:
struct slice {
const char *p;
int length;
};
You can then safely return slices of the original string without needing to worry about additional memory.
You can also use the standard functions in most cases, if you stick to the strn variants. When you print a slice, you can do so by specifying a field width in printf formats:
printf("Second part: '%.*s'\n", s->length, s->p);
In your parttwo() function you return the address of a local variable
return rightSide;
where rightSide is a pointer to a local variable.
It appears that your compiler gave you a warning about this which you solved by making a pointer to the local variabe arrayRight, that may confuse the compiler but the result will be the same, the data in arrayRight will no longer exist after the function returns.
You are doing the same all over your code, and even worse, in the secondexp() function you return a the address of a local variable taking it's address, you are not only returning the address to a local variabel, but also with a type that is not compatible with the return type of the function.
This is one of many probable issues that your code may have, but you need to start fixing that to continue with other possible problems.
Note: enable extra warnings when compiler and listen to them, don't try to fool the compiler unless you know exactly what you're doing.

qsort works incorrectly (compare function)

I write program which sort numbers like 23.44 12.4223. And almost everything works fine but it does not sort correctly numbers for instance 24.321 and 24.33 i mean for my rpgoram 24.321 is greater than 24.33
Infile contains numbers like 34.5 123.55. 56. .43 564.3
Here's my code:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define NUMBER_CHUNK 13
char* getNumber(FILE* fp)
{
int length;
int current = 0;
int c;
char *number, *number2;
number = (char*)malloc(sizeof(char)*NUMBER_CHUNK);
if(!number)
{
printf("Error while allocating memory!\n");
return NULL;
}
length = NUMBER_CHUNK;
while(!isspace(c = fgetc(fp)) && !feof(fp))
{
if(isdigit(c) || c == '.')
{
number[current] = c;
current++;
if(current >= length)
{
length+=NUMBER_CHUNK;
number2 = (char*)realloc(number,sizeof(char*)*length);
if(number2 == NULL)
{
free(number2);
return NULL;
}
else number2 = number;
}
}
else
{
return NULL;
}
}
number[current] = '\0';
return number;
}
int compare(const void *str1, const void *str2)
{
char* curr1;
char* curr2;
int value = 0;
size_t len1 = 0;
size_t len2 = 0;
curr1=*(char**)str1;
curr2=*(char**)str2;
while(*curr1=='0' || *curr1=='.') curr1++;
while(*curr2=='0' || *curr2=='.') curr2++;
while(*curr1 || *curr2)
{
while(*curr1 == '.')
curr1++;
while(*curr2 == '.')
curr2++;
if(value == 0)
{
value = *curr1 - *curr2;
}
if(*curr1)
{
curr1++;
len1++;
}
if(*curr2)
{
curr2++;
len2++;
}
}
if(len1 != len2)
{
return (len1 > len2) ? 1 : -1;
}
return value;
}
int main(int argc, char** argv)
{
FILE* fp;
char** tab;
int i = 0;
int lines = 0;
int length = 10;
if(argc != 2)
{
printf("Incorrent syntax! Use ./program_name input_file\n");
return 1;
}
if(!(fp = fopen(argv[1],"r")))
{
printf("Could not open the file! Please try again!\n");
return 2;
}
tab = (char**)malloc(length*(sizeof(char*)));
if(!tab)
{
printf("Could not allocate memory!\n");
free(tab);
return 3;
}
while(!feof(fp))
{
tab[i] = getNumber(fp);
if(i >= length)
{
length += 10;
tab = (char**)realloc(tab,sizeof(char*));
if(tab == NULL)
{
free(tab);
return 5;
}
}
if(tab[i] == NULL)
{
printf("Incorrect character in the infile! Terminating\n");
free(tab);
return 4;
}
if(*tab[i] == '\0')
{
free(tab[i]);
i--;
}
i++;
lines = i;
}
printf("\nBEFORE\n");
for(i = 0 ; i < lines; i++)
{
printf("%s\n", tab[i]);
}
qsort(tab, lines, sizeof(char*), compare);
printf("\nAFTER\n");
for(i = 0; i < lines; i++)
{
printf("%s\n",tab[i]);
free(tab[i]);
}
printf("\n");
free(tab);
fclose(fp);
return 0;
}
In your program 24.321 is greater than 24.33 because length of 24.321 is greater than length of 24.33.
You should stop increasing length when you read ..
Fix:
//UPDATE
while(*curr1=='0') curr1++;
while(*curr2=='0') curr2++;
//END OF UPDATE
char dot1 = 0, dot2 = 0;
char err1 = 0, err2 = 0;
while(*curr1 || *curr2)
{
if(*curr1 == '.') ++dot1; //UPDATE2
if(*curr2 == '.') ++dot2; //UPDATE2
while(*curr1 == '.')
curr1++;
while(*curr2 == '.')
curr2++;
if(value == 0)
{
value = *curr1 - *curr2;
}
if(*curr1)
{
if(*curr1 < '0' || *curr1 > '9') err1 = 1;
curr1++;
if(!dot1) len1++;
}
if(*curr2)
{
if(*curr2 < '0' || *curr2 > '9') err2 = 1;
curr2++;
if(!dot2) len2++;
}
}
if(err1 || err2 || dot1 > 1 || dot2 > 1) exit(1); // UPDATE2
UPDATE:
I updated code. Now before main comparison while only zeros are skipped. Dots will be skipped at the beginning of main while and fix with dot1 and dot2 will work.
UPDATE2:
To check if numbers are correct you should count dots and check if all chars are dots or digits.
Be aware that for longer bad numbers (more than 255 dots) my code could not work correctly (because dot1 is 1 byte long). If you need to handle these cases you should check if dot1/dot2 are equal to 1 and change err1/err2 to 1 instead of increasing dot1/dot2.
Your problem is here:---
if(len1 != len2)
{
return (len1 > len2) ? 1 : -1;
}
For strings "24.321" len1 = 6 ,"24.33" len2 = 5 so the longest string wins.
I thing your algorithm will also encounter problems with 123.45 vs 23.456 as you are basically ignoring the decimal point.
You could try converting to floating point (use function atof() or strtof() ) to convert the string to a real real number then compare.
Or simply return "less than" if you encounter a '.' in the first string before you encounter it in the second string.

Resources