开发者

Objective c, Scanf() string taking in the same value twice

Hi all I am having a strange issue, when i use scanf to input data it repeats strings and saves them as one i am not sure why.

Please Help

/* Assment Label loop - Loops through the assment labels and inpu开发者_如何学Gots the percentage and the name for it. */

i = 0;
j = 0;
while (i < totalGradedItems)
{
    scanf("%s%d",  assLabel[i], &assPercent[i]);
    i++;
}

/* Print Statement */

i = 0;
while (i < totalGradedItems)
{
    printf("%s", assLabel[i]);
    i++;
}

Input Data

Prog1 20
Quiz 20
Prog2 20
Mdtm 15
Final 25

Output Via Console

Prog1QuizQuizProg2MdtmMdtmFinal


Final diagnosis

You don't show your declarations...but you must be allocating just 5 characters for the strings:

When I adjust the enum MAX_ASSESSMENTLEN from 10 to 5 (see the code below) I get the output:

Prog1Quiz  20
Quiz       20
Prog2Mdtm  20
Mdtm       15
Final      25

You did not allow for the terminal null. And you didn't show us what was causing the bug! And the fact that you omitted newlines from the printout obscured the problem.

What's happening is that 'Prog1' is occupying all 5 bytes of the string you read in, and is writing a null at the 6th byte; then Quiz is being read in, starting at the sixth byte. When printf() goes to read the string for 'Prog1', it stops at the first null, which is the one after the 'z' of 'Quiz', producing the output shown. Repeat for 'Prog2' and 'Mtdm'. If there was an entry after 'Final', it too would suffer. You are lucky that there are enough zero bytes around to prevent any monstrous overruns.

This is a basic buffer overflow (indeed, since the array is on the stack, it is a basic Stack Overflow); you are trying to squeeze 6 characters (Prog1 plus '\0') into a 5 byte space, and it simply does not work well.


Preliminary diagnosis

First, print newlines after your data.

Second, check that scanf() is not returning errors - it probably isn't, but neither you nor we can tell for sure.

Third, are you sure that the data file contains what you say? Plausibly, it contains a pair of 'Quiz' and a pair of 'Mtdm' lines.

Your variable j is unused, incidentally.

You would probably be better off having the input loop run until you are either out of space in the receiving arrays or you get a read failure. However, the code worked for me when dressed up slightly:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    char assLabel[10][10];
    int  assPercent[10];

    int i = 0;
    int totalGradedItems = 5;

    while (i < totalGradedItems)
    {
        if (scanf("%9s%d",  assLabel[i], &assPercent[i]) != 2)
        {
            fprintf(stderr, "Error reading\n");
            exit(1);
        }
        i++;
    }

    /* Print Statement */

    i = 0;
    while (i < totalGradedItems)
    {
        printf("%-9s %3d\n", assLabel[i], assPercent[i]);
        i++;
    }

    return 0;
}

For the quoted input data, the output results are:

Prog1      20
Quiz       20
Prog2      20
Mdtm       15
Final      25

I prefer this version, though:

#include <stdio.h>

enum { MAX_GRADES = 10 };
enum { MAX_ASSESSMENTLEN = 10 };

int main(void)
{
    char assLabel[MAX_GRADES][MAX_ASSESSMENTLEN];
    int  assPercent[MAX_GRADES];
    int i = 0;
    int totalGradedItems;

    for (i = 0; i < MAX_GRADES; i++)
    {
        if (scanf("%9s%d", assLabel[i], &assPercent[i]) != 2)
            break;
    }
    totalGradedItems = i;

    for (i = 0; i < totalGradedItems; i++)
        printf("%-9s %3d\n", assLabel[i], assPercent[i]);

    return 0;
}

Of course, if I'd set up the scanf() format string 'properly' (meaning safely) so as to limit the length of the assessment names to fit into the space allocated, then the loop would stop reading on the second attempt:

...
char format[10];
...
snprintf(format, sizeof(format), "%%%ds%%d", MAX_ASSESSMENTLEN-1);
...
    if (scanf(format, assLabel[i], &assPercent[i]) != 2)

With MAX_ASSESSMENTLEN at 5, the snprintf() generates the format string "%4s%d". The code compiled reads:

Prog       1

and stops. The '1' comes from the 5th character of 'Prog1'; the next assessment name is '20', and then the conversion of 'Quiz' into a number fails, causing the input loop to stop (because only one of two expected items was converted).

Despite the nuisance value, if you want to make your scanf() strings adjust to the size of the data variables it is reading into, you have to do something akin to what I did here - format the string using the correct size values.


i guess, you need to put a

scanf("%s%d",  assLabel[i], &assPercent[i]);

space between %s and %d here.

And it is not saving as one. You need to put newline or atlease a space after %s on print to see difference.

add:

when i tried

#include <stdio.h>

int main (int argc, const char * argv[])
{

    char a[1][2];

    for(int i =0;i<3;i++)
    scanf("%s",a[i]);

    for(int i =0;i<3;i++)
        printf("%s",a[i]);
    return 0;
}

with inputs

123456
qwerty
sdfgh

output is:

12qwsdfghqwsdfghsdfgh

that proves that, the size of string array need to be bigger then decleared there.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜