The baron
The baron

Reputation: 35

C read string with fgets from 1 and keep 0 available for reading

I'm working on a function in C that gets a number from the user and converts it into a string, putting in the beginning of the string - + or nothing (if 0) than printing the length of the string and the string itself.

So lets say I enter "123", the string will contain: '+','1','2','3','\0' and it will print: "The array length is 4 and it contain +123" with minus it will print the same thing just with - at the beginning (-123) and with 0 it wont print any thing (0)

That is the code I made:

#define STRING_SIZE 100

int main ()
{
    int num;
    char sNum[STRING_SIZE] = {'\0'}, string[STRING_SIZE] = {'\0'};
    printf("%s", string);
    scanf("%d", &num);
    itoa(num, string, 10);

    if (num < 0) {
        sNum[0] = '-';
    }
    else if (num > 0) {
        sNum[0] = '+';
    }
    strncpy (sNum, string, STRING_SIZE);
    printf("\nThe string length is %d and contains the number: %s\n", strlen(sNum), sNum);

    system ("PAUSE");
    return 0;
}

And that is my output when I enter 123:

The string length is 3 and contains the number: 123

Upvotes: 1

Views: 57

Answers (3)

Danny_ds
Danny_ds

Reputation: 11406

strncpy (sNum,string,STRING_SIZE);

This overwrites the original value (with the sign).

Use strcat instead, but make sure sNum[1] == '\0'.

Something like this:

char sNum[STRING_SIZE + 1] = {'\0'}, string[STRING_SIZE] = {'\0'};

// ...

if (num != 0) {
    sNum[0] = (num < 0) ? '-' : '+';    
}
strcat(sNum, string);

Upvotes: 2

Iharob Al Asimi
Iharob Al Asimi

Reputation: 53016

You don't need to convert it to a string check this

#include <stdio.h>

int main(void)
{
    int value;
    int length;
    if (scanf("%d%n", &value, &length) != 1)
        return -1;
    if (value == 0)
        printf("The string length is `1' and contains the number `0'\n");
    else
        printf("The string length is `%d' and contains the number `%+d'\n",
            length, value);
    return 0;
}

Explanation:

  1. The "%n" specifier in scanf() stores in length the number of characters scanf() read.
  2. The printf() "+" modifier adds a + in front of positive numbers and a - in front of negative numbers. The special value 0 is handled separately.
  3. Always check the return value of scanf().

Upvotes: 1

Some programmer dude
Some programmer dude

Reputation: 409442

You copy over the character you set in sNum. You need to copy beginning at the second character of sNum, i.e. &sNum[1]. Also remember to copy one less character from string. Also remember that there is a case where strncpy will not append the terminator.

Or just use snprintf:

snprintf(sNum, sizeof(sNum), "%+d", num);

Upvotes: 4

Related Questions