Sponsored Content
Top Forums Programming Logical Error With Type Conversion In C Post 303021887 by Azrael on Monday 20th of August 2018 12:07:39 AM
Old 08-20-2018
Logical Error With Type Conversion In C

So, I'm into about 650 lines of some code I'm working on. So I'll try to explain instead of flooding this post. Say I have some code like this:

Code:
int main() {
    int i, j;
    char data[INPUT_BUFF];

    printf("Gimme something: ");
    fgets(data, INPUT_BUFF, stdin);

    for (j = 0; j < data[INPUT_BUFF]; j++){
    switch(data[j]){
    case 0: 
        if(j == 'e'){
            atoi(data);
            data[j] = ranit(e_array);
            sprintf( data, "%d", data );
        }
    case 1: 
        if(j == 'm'){
            atoi(data);
            data[j] = ranit(m_array);
            sprintf( data, "%d", data );
        }
    case 2: 
        if(j == 'n'){
            atoi(data);
            data[j] = ranit(n_array);
            sprintf( data, "%d", data );
        }
    case 3: 
        if(j == 'o'){
            atoi(data);
            data[j] = ranit(o_array);
            sprintf( data, "%d", data );
        }
    case 4: 
        if(j == 'y'){
            atoi(data);
            data[j] = ranit(y_array);
            sprintf( data, "%d", data );
        }

     }
     }

     for (i = 0; i < INPUT_BUFF; i++){
         printf("%x\n", (int)data[(int)i]);
     }

     return 0;
}

I have a switch statement in the above that only checks for the characters in the word 'money'. The entire alphabet would have been too much to put here. The function ranit() grabs a random element out of the array it is past. That function has been checked and works perfect. In the case all the elements are numbers. I've tried to do this a lot of different ways, but what I want to do is after checking for a matching character, replace it with a random element in from the corresponding arrays that contain integers.

I tried using atoi() to make the 'data' character array able to hold integers. That way I wouldn't get an error about mismatching types. At some point I could have sworn itoa worked with gcc, but I now see this is no longer part of the standard library. I tried using sprintf() to convert the data array back to chars for the next iteration of the loop.

When I run the code I notice the random numbers aren't displayed, but the hex equivalents for the ascii values of the word 'money':

Code:
$ ./test 
Gimme something: money
6d
6f
6e
65
79

I'm unsure if I'm assigning the values wrong or if sprintf won't allow for the same source and destination values. All the examples I found would put this in a new variable or array name, but I need to have it in the same for the next loop iteration. So maybe I should be using something else?

No warnings or errors from the compiler. Just strictly a logical error at this point. Any suggestions much appreciated.
 

9 More Discussions You Might Find Interesting

1. UNIX for Dummies Questions & Answers

Error in creating logical partition

Dear Members, I am using SCO-Unix 5.0.5. I have created 2 logical drives but some of the blocks are overlapped and are now giving warning during startup. I have used fsck to settle the problems but to no avail. Kindly help me to sort out the problem. Thanks (3 Replies)
Discussion started by: nagendrajaiswal
3 Replies

2. Shell Programming and Scripting

Does KSH support data type conversion?

Hello,everyone here. I'm coding with KSH to achieve exploring the disk space and judging whether it closes to overflow.But It seems that no one way to convert a string variable to integer. df | read A B C D E F G H I J K L print ${L} Can I convert L to integer type? Thanks for... (2 Replies)
Discussion started by: joshuaduan
2 Replies

3. Shell Programming and Scripting

error during run: St9bad_alloc - Getting this error while using some conversion progr

Hi all, It will be very useful If you spare some time with me for this worrying error. I am calling a conversion program which is written in C++ for converting a file format to different format. It was working fine for this past 2 yrs. But now it is not working since the file size has been... (1 Reply)
Discussion started by: sathu_pec
1 Replies

4. AIX

Type of Logical Volume lost after vgexport/gvimport process

Hi, I have the next doubt about of lost of characteristic of LV in my original configuration # lsvg -l ifxvg ifxvg: LV NAME TYPE LPs PPs PVs LV STATE MOUNT POINT aw64m_01 jfs 1 1 1 open/syncd N/A aw64m_02 jfs 1... (1 Reply)
Discussion started by: cerber0
1 Replies

5. UNIX for Dummies Questions & Answers

Build Error: error: dereferencing pointer to incomplete type

I'm getting the following Error: prepare_pcap.c: In function `prepare_pkts': prepare_pcap.c:127: error: dereferencing pointer to incomplete type prepare_pcap.c:138: error: dereferencing pointer to incomplete type ==================================== This is the part of the relevant... (8 Replies)
Discussion started by: katwala
8 Replies

6. Shell Programming and Scripting

Logical error

I have this script to uvscan-update. Seems like that i am getting logical error at the end of the script. It is updating the script and also giving the error message to update it manually. I have deleted the DAT files to see if it will create new and it does. Below is the error and the script: ... (1 Reply)
Discussion started by: mk07md
1 Replies

7. Shell Programming and Scripting

Military type format date/time conversion

Hello All, I have a requirement to convert a 12 hour format to 24 hour time format and the sample input /out put is below Input Time format : Nov 2 2011 12:16AM Out Put Format : Nov 2 2011 0:16 Input : Nov 2 2011 4:16PM Out Put: Nov 2 2011 16:16 I have done this using a... (6 Replies)
Discussion started by: jambesh
6 Replies

8. Programming

type conversion C, atoi()

In the book "The C programming language"; second edition, chapter 2.7 there is a snippet which is supposed to: "convert a string of digits into its numeric equivalent". int atoi(char s) { int i, n; n = 0; for ( i = 0; s >= '0' && s <= '9'; ++i) n = 10 * n + (s -... (4 Replies)
Discussion started by: tornow
4 Replies

9. Shell Programming and Scripting

Logical if error

Hi All, I am writing a simple script to read a file and display the lines with char count between 20 and 25. I am stuck with the if condition here. Tried a lot but still getting an error on the if condition # if && if && My script is very simple as below, not able to understand... (7 Replies)
Discussion started by: nss280
7 Replies
SPRINTF(3)								 1								SPRINTF(3)

sprintf - Return a formatted string

SYNOPSIS
string sprintf (string $format, [mixed $args], [mixed $...]) DESCRIPTION
Returns a string produced according to the formatting string $format. PARAMETERS
o $format - The format string is composed of zero or more directives: ordinary characters (excluding %) that are copied directly to the result, and conversion specifications, each of which results in fetching its own parameter. This applies to both sprintf(3) and printf(3). Each conversion specification consists of a percent sign ( %), followed by one or more of these elements, in order: o An optional sign specifier that forces a sign (- or +) to be used on a number. By default, only the - sign is used on a number if it's negative. This specifier forces positive numbers to have the + sign attached as well, and was added in PHP 4.3.0. o An optional padding specifier that says what character will be used for padding the results to the right string size. This may be a space character or a 0 (zero character). The default is to pad with spaces. An alternate padding character can be specified by prefixing it with a single quote ( '). See the examples below. o An optional alignment specifier that says if the result should be left-justified or right-justified. The default is right-justified; a - character here will make it left-justified. o An optional number, a width specifier that says how many characters (minimum) this conversion should result in. o An optional precision specifier in the form of a period ( .) followed by an optional decimal digit string that says how many decimal digits should be displayed for floating-point numbers. When using this specifier on a string, it acts as a cutoff point, setting a maximum character limit to the string. Additionally, the character to use when padding a number may optionally be specified between the period and the digit. o A type specifier that says what type the argument data should be treated as. Possible types: o % - a literal percent character. No argument is required. o b - the argument is treated as an integer, and presented as a binary number. o c - the argument is treated as an integer, and presented as the character with that ASCII value. o d - the argument is treated as an integer, and presented as a (signed) decimal number. o e - the argument is treated as scientific notation (e.g. 1.2e+2). The precision specifier stands for the number of digits after the decimal point since PHP 5.2.1. In earlier versions, it was taken as number of significant digits (one less). o E - like %e but uses uppercase letter (e.g. 1.2E+2). o f - the argument is treated as a float, and presented as a floating-point number (locale aware). o F - the argument is treated as a float, and presented as a floating-point number (non-locale aware). Available since PHP 4.3.10 and PHP 5.0.3. o g - shorter of %e and %f. o G - shorter of %E and %f. o o - the argument is treated as an integer, and presented as an octal number. o s - the argument is treated as and presented as a string. o u - the argument is treated as an integer, and presented as an unsigned decimal number. o x - the argument is treated as an integer and presented as a hexadecimal number (with lowercase letters). o X - the argument is treated as an integer and presented as a hexadecimal number (with uppercase letters). Variables will be co-erced to a suitable type for the specifier: Type Handling +--------+---------------------+ | Type | | | | | | | Specifiers | | | | +--------+---------------------+ | | | |string | | | | | | | | | | s | | | | | | | |integer | | | | | | | | | | d, u, c, o, x, X, b | | | | | | | |double | | | | | | | | | | g, G, e, E, f, F | | | | +--------+---------------------+ Warning Attempting to use a combination of the string and width specifiers with character sets that require more than one byte per character may result in unexpected results The format string supports argument numbering/swapping. Here is an example: Example #1 Argument swapping <?php $num = 5; $location = 'tree'; $format = 'There are %d monkeys in the %s'; echo sprintf($format, $num, $location); ?> This will output "There are 5 monkeys in the tree". But imagine we are creating a format string in a separate file, commonly because we would like to internationalize it and we rewrite it as: Example #2 Argument swapping <?php $format = 'The %s contains %d monkeys'; echo sprintf($format, $num, $location); ?> We now have a problem. The order of the placeholders in the format string does not match the order of the arguments in the code. We would like to leave the code as is and simply indicate in the format string which arguments the placeholders refer to. We would write the format string like this instead: Example #3 Argument swapping <?php $format = 'The %2$s contains %1$d monkeys'; echo sprintf($format, $num, $location); ?> An added benefit here is that you can repeat the placeholders without adding more arguments in the code. For example: Example #4 Argument swapping <?php $format = 'The %2$s contains %1$d monkeys. That's a nice %2$s full of %1$d monkeys.'; echo sprintf($format, $num, $location); ?> When using argument swapping, the n$ position specifier must come immediately after the percent sign ( %), before any other speci- fiers, as shown in the example below. Example #5 Specifying padding character <?php echo sprintf("%'.9d ", 123); echo sprintf("%'.09d ", 123); ?> The above example will output: 000000123 Example #6 Position specifier with other specifiers <?php $format = 'The %2$s contains %1$04d monkeys'; echo sprintf($format, $num, $location); ?> The above example will output: The tree contains 0005 monkeys Note Attempting to use a position specifier greater than PHP_INT_MAX will result in sprintf(3) generating warnings. Warning The c type specifier ignores padding and width o $args - o $... - RETURN VALUES
Returns a string produced according to the formatting string $format. EXAMPLES
Example #7 printf(3): various examples <?php $n = 43951789; $u = -43951789; $c = 65; // ASCII 65 is 'A' // notice the double %%, this prints a literal '%' character printf("%%b = '%b' ", $n); // binary representation printf("%%c = '%c' ", $c); // print the ascii character, same as chr() function printf("%%d = '%d' ", $n); // standard integer representation printf("%%e = '%e' ", $n); // scientific notation printf("%%u = '%u' ", $n); // unsigned integer representation of a positive integer printf("%%u = '%u' ", $u); // unsigned integer representation of a negative integer printf("%%f = '%f' ", $n); // floating point representation printf("%%o = '%o' ", $n); // octal representation printf("%%s = '%s' ", $n); // string representation printf("%%x = '%x' ", $n); // hexadecimal representation (lower-case) printf("%%X = '%X' ", $n); // hexadecimal representation (upper-case) printf("%%+d = '%+d' ", $n); // sign specifier on a positive integer printf("%%+d = '%+d' ", $u); // sign specifier on a negative integer ?> The above example will output: %b = '10100111101010011010101101' %c = 'A' %d = '43951789' %e = '4.39518e+7' %u = '43951789' %u = '4251015507' %f = '43951789.000000' %o = '247523255' %s = '43951789' %x = '29ea6ad' %X = '29EA6AD' %+d = '+43951789' %+d = '-43951789' Example #8 printf(3): string specifiers <?php $s = 'monkey'; $t = 'many monkeys'; printf("[%s] ", $s); // standard string output printf("[%10s] ", $s); // right-justification with spaces printf("[%-10s] ", $s); // left-justification with spaces printf("[%010s] ", $s); // zero-padding works on strings too printf("[%'#10s] ", $s); // use the custom padding character '#' printf("[%10.10s] ", $t); // left-justification but with a cutoff of 10 characters ?> The above example will output: [monkey] [ monkey] [monkey ] [0000monkey] [####monkey] [many monke] Example #9 sprintf(3): zero-padded integers <?php $isodate = sprintf("%04d-%02d-%02d", $year, $month, $day); ?> Example #10 sprintf(3): formatting currency <?php $money1 = 68.75; $money2 = 54.35; $money = $money1 + $money2; // echo $money will output "123.1"; $formatted = sprintf("%01.2f", $money); // echo $formatted will output "123.10" ?> Example #11 sprintf(3): scientific notation <?php $number = 362525200; echo sprintf("%.3e", $number); // outputs 3.625e+8 ?> SEE ALSO
printf(3), sscanf(3), fscanf(3), vsprintf(3), number_format(3). PHP Documentation Group SPRINTF(3)
All times are GMT -4. The time now is 01:37 AM.
Unix & Linux Forums Content Copyright 1993-2022. All Rights Reserved.
Privacy Policy