Example #1
0
/**
 * @brief Sets the value of str to the value of the integer n.
 *	(i.e. if n=7 than str should contain ‘7’)
 * @param str the MyString to set.
 * @param n the int to set from.
 * RETURN VALUE:
 *  @return MYSTRING_SUCCESS on success, MYSTRING_ERROR on failure.
 */
MyStringRetVal myStringSetFromInt(MyString *str, int n)
{
    unsigned int length = getIntLength(n);

    if (str == NULL)
    {
        return MYSTRING_ERROR;
    }

    if (mystringRealloc(str, length) == MYSTRING_ERROR)
    {
        return MYSTRING_ERROR;
    }

    char *tempStr = (char *)malloc(sizeof(char) * C_STRING_LENGTH);

    if (tempStr == NULL)
    {
        return MYSTRING_ERROR;
    }

    snprintf(tempStr, length, "%d", n);

    if (myStringSetFromCString(str, tempStr) == MYSTRING_ERROR)
    {
        return MYSTRING_ERROR;
    }

    free(tempStr);
    tempStr = NULL;

    return MYSTRING_SUCCESS;
}
Example #2
0
/**
 * @brief Asks for 2 strings, compare between them and write to file the results.
 */
int main()
{
	char str1[MAX_LENGTH] = {0}, str2[MAX_LENGTH] = {0};
	printf("Enter the first string:\n");
	fgets(str1, MAX_LENGTH, stdin);
	printf("Enter the second string:\n");
	fgets(str2, MAX_LENGTH, stdin);

	// Replace the last char '\n' that fgets automatic puts in the end of the strings with '\0'
	int lenStr1 = strlen(str1);
	int lenStr2 = strlen(str2);

	str1[lenStr1 - 1] = '\0';
	str2[lenStr2 - 1] = '\0';

	MyString* myStr1 = myStringAlloc();
	MyString* myStr2 = myStringAlloc();

	myStringSetFromCString(myStr1, str1);
	myStringSetFromCString(myStr2, str2);

	printf("Compare between the 2 strings and writing the result to test.out...\n");

	int compare = myStringCompare(myStr1, myStr2);

	if (compare <= 0)
	{
		writeResult(myStr1, myStr2);
	}
	else
	{
		writeResult(myStr2, myStr1);
	}

	printf("Done.\n");

	myStringFree(myStr1);
	myStringFree(myStr2);
	return 0;
}
Example #3
0
/**
 * Create a string, clone it and compare them
 */
void test1()
{
    // for the sake of clarity, we don't check for errors in this demonstration

    // this function call allocates a number and sets it to 0
    MyString * s1 = myStringAlloc();
	MyStringRetVal rVal = myStringSetFromCString(s1, "Hello world?!?");
	MyString * s2 = myStringClone(s1);
	
	int res = myStringCompare(s1, s2);
	
	if (res != 0) 
	{
        exitBad(1);
    
    }

    myStringFree(s1);
    myStringFree(s2);
}