2d array giving wrong output











up vote
1
down vote

favorite












I was writing a code to print all the strings stored in 2d array after the user has finished typing the strings along with mentioning the maxlength of each string and total number strings (it will finally print the string along with the line number). The problem is that the code actually stores all the strings in the 2d array with one whole line of spacing i.e, one full empty row. The code, expected output and the output it is giving is below.



Code:



#include <stdio.h>

int main() {
char s[20][30];
int i, number_of_strings, length_of_string, j = 0;
scanf("%d %d", &number_of_strings, &length_of_string);

for (i = 0; i<number_of_strings; i++) {
while ((s[i][j++] = getchar()) != 'n' && j<length_of_string)
s[i][j] = '';
j = 0;
}

for (i = 0; i<number_of_strings; i++) {
printf("i= %d %sn", i, s[i]);
}

return 0;
}


Sample Input:



2 3
raj
jar


Expected Output:



i= 0   raj
i= 1 jar


Output giving:



i= 0   

i= 1 raj
i= 2

i= 3 jar


Please rectify where am I doing mistake.










share|improve this question




















  • 1




    Do you realize you have a newline stuck in your input buffer after you second int read ? what do you suppose that does to your first loop iteration ?
    – WhozCraig
    Nov 12 at 8:02






  • 1




    You need to eat the n before it consumes in your next iteration.
    – jack jay
    Nov 12 at 8:04






  • 1




    scanf("%d %d", &number_of_strings, &length_of_string); leaves the n of 2 3n in the buffer and the first getchar() reads it.
    – mch
    Nov 12 at 8:04






  • 1




    while ((s[i][j++] = getchar()) != 'n' && j<length_of_string) s[i][j] = ''; ==> size test first as (j + 1) <length_of_string
    – chux
    Nov 12 at 8:04








  • 1




    @KaustavBhattacharjee n is in your buffer. This is the problem.
    – jack jay
    Nov 12 at 8:06

















up vote
1
down vote

favorite












I was writing a code to print all the strings stored in 2d array after the user has finished typing the strings along with mentioning the maxlength of each string and total number strings (it will finally print the string along with the line number). The problem is that the code actually stores all the strings in the 2d array with one whole line of spacing i.e, one full empty row. The code, expected output and the output it is giving is below.



Code:



#include <stdio.h>

int main() {
char s[20][30];
int i, number_of_strings, length_of_string, j = 0;
scanf("%d %d", &number_of_strings, &length_of_string);

for (i = 0; i<number_of_strings; i++) {
while ((s[i][j++] = getchar()) != 'n' && j<length_of_string)
s[i][j] = '';
j = 0;
}

for (i = 0; i<number_of_strings; i++) {
printf("i= %d %sn", i, s[i]);
}

return 0;
}


Sample Input:



2 3
raj
jar


Expected Output:



i= 0   raj
i= 1 jar


Output giving:



i= 0   

i= 1 raj
i= 2

i= 3 jar


Please rectify where am I doing mistake.










share|improve this question




















  • 1




    Do you realize you have a newline stuck in your input buffer after you second int read ? what do you suppose that does to your first loop iteration ?
    – WhozCraig
    Nov 12 at 8:02






  • 1




    You need to eat the n before it consumes in your next iteration.
    – jack jay
    Nov 12 at 8:04






  • 1




    scanf("%d %d", &number_of_strings, &length_of_string); leaves the n of 2 3n in the buffer and the first getchar() reads it.
    – mch
    Nov 12 at 8:04






  • 1




    while ((s[i][j++] = getchar()) != 'n' && j<length_of_string) s[i][j] = ''; ==> size test first as (j + 1) <length_of_string
    – chux
    Nov 12 at 8:04








  • 1




    @KaustavBhattacharjee n is in your buffer. This is the problem.
    – jack jay
    Nov 12 at 8:06















up vote
1
down vote

favorite









up vote
1
down vote

favorite











I was writing a code to print all the strings stored in 2d array after the user has finished typing the strings along with mentioning the maxlength of each string and total number strings (it will finally print the string along with the line number). The problem is that the code actually stores all the strings in the 2d array with one whole line of spacing i.e, one full empty row. The code, expected output and the output it is giving is below.



Code:



#include <stdio.h>

int main() {
char s[20][30];
int i, number_of_strings, length_of_string, j = 0;
scanf("%d %d", &number_of_strings, &length_of_string);

for (i = 0; i<number_of_strings; i++) {
while ((s[i][j++] = getchar()) != 'n' && j<length_of_string)
s[i][j] = '';
j = 0;
}

for (i = 0; i<number_of_strings; i++) {
printf("i= %d %sn", i, s[i]);
}

return 0;
}


Sample Input:



2 3
raj
jar


Expected Output:



i= 0   raj
i= 1 jar


Output giving:



i= 0   

i= 1 raj
i= 2

i= 3 jar


Please rectify where am I doing mistake.










share|improve this question















I was writing a code to print all the strings stored in 2d array after the user has finished typing the strings along with mentioning the maxlength of each string and total number strings (it will finally print the string along with the line number). The problem is that the code actually stores all the strings in the 2d array with one whole line of spacing i.e, one full empty row. The code, expected output and the output it is giving is below.



Code:



#include <stdio.h>

int main() {
char s[20][30];
int i, number_of_strings, length_of_string, j = 0;
scanf("%d %d", &number_of_strings, &length_of_string);

for (i = 0; i<number_of_strings; i++) {
while ((s[i][j++] = getchar()) != 'n' && j<length_of_string)
s[i][j] = '';
j = 0;
}

for (i = 0; i<number_of_strings; i++) {
printf("i= %d %sn", i, s[i]);
}

return 0;
}


Sample Input:



2 3
raj
jar


Expected Output:



i= 0   raj
i= 1 jar


Output giving:



i= 0   

i= 1 raj
i= 2

i= 3 jar


Please rectify where am I doing mistake.







c multidimensional-array output






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 12 at 8:03

























asked Nov 12 at 7:57









Kaustav Bhattacharjee

114




114








  • 1




    Do you realize you have a newline stuck in your input buffer after you second int read ? what do you suppose that does to your first loop iteration ?
    – WhozCraig
    Nov 12 at 8:02






  • 1




    You need to eat the n before it consumes in your next iteration.
    – jack jay
    Nov 12 at 8:04






  • 1




    scanf("%d %d", &number_of_strings, &length_of_string); leaves the n of 2 3n in the buffer and the first getchar() reads it.
    – mch
    Nov 12 at 8:04






  • 1




    while ((s[i][j++] = getchar()) != 'n' && j<length_of_string) s[i][j] = ''; ==> size test first as (j + 1) <length_of_string
    – chux
    Nov 12 at 8:04








  • 1




    @KaustavBhattacharjee n is in your buffer. This is the problem.
    – jack jay
    Nov 12 at 8:06
















  • 1




    Do you realize you have a newline stuck in your input buffer after you second int read ? what do you suppose that does to your first loop iteration ?
    – WhozCraig
    Nov 12 at 8:02






  • 1




    You need to eat the n before it consumes in your next iteration.
    – jack jay
    Nov 12 at 8:04






  • 1




    scanf("%d %d", &number_of_strings, &length_of_string); leaves the n of 2 3n in the buffer and the first getchar() reads it.
    – mch
    Nov 12 at 8:04






  • 1




    while ((s[i][j++] = getchar()) != 'n' && j<length_of_string) s[i][j] = ''; ==> size test first as (j + 1) <length_of_string
    – chux
    Nov 12 at 8:04








  • 1




    @KaustavBhattacharjee n is in your buffer. This is the problem.
    – jack jay
    Nov 12 at 8:06










1




1




Do you realize you have a newline stuck in your input buffer after you second int read ? what do you suppose that does to your first loop iteration ?
– WhozCraig
Nov 12 at 8:02




Do you realize you have a newline stuck in your input buffer after you second int read ? what do you suppose that does to your first loop iteration ?
– WhozCraig
Nov 12 at 8:02




1




1




You need to eat the n before it consumes in your next iteration.
– jack jay
Nov 12 at 8:04




You need to eat the n before it consumes in your next iteration.
– jack jay
Nov 12 at 8:04




1




1




scanf("%d %d", &number_of_strings, &length_of_string); leaves the n of 2 3n in the buffer and the first getchar() reads it.
– mch
Nov 12 at 8:04




scanf("%d %d", &number_of_strings, &length_of_string); leaves the n of 2 3n in the buffer and the first getchar() reads it.
– mch
Nov 12 at 8:04




1




1




while ((s[i][j++] = getchar()) != 'n' && j<length_of_string) s[i][j] = ''; ==> size test first as (j + 1) <length_of_string
– chux
Nov 12 at 8:04






while ((s[i][j++] = getchar()) != 'n' && j<length_of_string) s[i][j] = ''; ==> size test first as (j + 1) <length_of_string
– chux
Nov 12 at 8:04






1




1




@KaustavBhattacharjee n is in your buffer. This is the problem.
– jack jay
Nov 12 at 8:06






@KaustavBhattacharjee n is in your buffer. This is the problem.
– jack jay
Nov 12 at 8:06














1 Answer
1






active

oldest

votes

















up vote
1
down vote



accepted










You've hit one of the many issues with scanf. In this case scanf("%d %d", ...) is leaving a newline on the buffer. You can get it to slurp in trailing whitespace with a space on the end.



scanf("%d %d ", &number_of_strings , &length_of_string); 


Then how you're reading a line is complicated. You can simplify it like so:



 int c, j;
for(j = 0; (c = getchar()) != 'n'; j++ ) {
s[i][j] = (char)c;
}
s[i][j] = '';


Or even simpler...



for(int i=0 ; i<number_of_strings ; i++) {
scanf("%29s", s[i]);
}


And there's no need for length_of_string. In fact, it's a liability since you've only allocated 30 bytes max. Similarly, number_of_strings can be higher than the allocated 20. It's better to read until input or memory is exhausted.



#include <stdio.h>

const int MAX_STRINGS = 20;
const int MAX_LENGTH = 30;
int main(){
char s[MAX_STRINGS][MAX_LENGTH];
int num_strings;
for(num_strings = 0; num_strings < MAX_STRINGS ; num_strings++) {
if( scanf("%29s", s[num_strings]) < 1 ) {
break;
}
}

for( int i = 0 ; i < num_strings; i++){
printf("i= %d %sn",i,s[i]);
}

return 0;
}





share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53257910%2f2d-array-giving-wrong-output%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    1
    down vote



    accepted










    You've hit one of the many issues with scanf. In this case scanf("%d %d", ...) is leaving a newline on the buffer. You can get it to slurp in trailing whitespace with a space on the end.



    scanf("%d %d ", &number_of_strings , &length_of_string); 


    Then how you're reading a line is complicated. You can simplify it like so:



     int c, j;
    for(j = 0; (c = getchar()) != 'n'; j++ ) {
    s[i][j] = (char)c;
    }
    s[i][j] = '';


    Or even simpler...



    for(int i=0 ; i<number_of_strings ; i++) {
    scanf("%29s", s[i]);
    }


    And there's no need for length_of_string. In fact, it's a liability since you've only allocated 30 bytes max. Similarly, number_of_strings can be higher than the allocated 20. It's better to read until input or memory is exhausted.



    #include <stdio.h>

    const int MAX_STRINGS = 20;
    const int MAX_LENGTH = 30;
    int main(){
    char s[MAX_STRINGS][MAX_LENGTH];
    int num_strings;
    for(num_strings = 0; num_strings < MAX_STRINGS ; num_strings++) {
    if( scanf("%29s", s[num_strings]) < 1 ) {
    break;
    }
    }

    for( int i = 0 ; i < num_strings; i++){
    printf("i= %d %sn",i,s[i]);
    }

    return 0;
    }





    share|improve this answer



























      up vote
      1
      down vote



      accepted










      You've hit one of the many issues with scanf. In this case scanf("%d %d", ...) is leaving a newline on the buffer. You can get it to slurp in trailing whitespace with a space on the end.



      scanf("%d %d ", &number_of_strings , &length_of_string); 


      Then how you're reading a line is complicated. You can simplify it like so:



       int c, j;
      for(j = 0; (c = getchar()) != 'n'; j++ ) {
      s[i][j] = (char)c;
      }
      s[i][j] = '';


      Or even simpler...



      for(int i=0 ; i<number_of_strings ; i++) {
      scanf("%29s", s[i]);
      }


      And there's no need for length_of_string. In fact, it's a liability since you've only allocated 30 bytes max. Similarly, number_of_strings can be higher than the allocated 20. It's better to read until input or memory is exhausted.



      #include <stdio.h>

      const int MAX_STRINGS = 20;
      const int MAX_LENGTH = 30;
      int main(){
      char s[MAX_STRINGS][MAX_LENGTH];
      int num_strings;
      for(num_strings = 0; num_strings < MAX_STRINGS ; num_strings++) {
      if( scanf("%29s", s[num_strings]) < 1 ) {
      break;
      }
      }

      for( int i = 0 ; i < num_strings; i++){
      printf("i= %d %sn",i,s[i]);
      }

      return 0;
      }





      share|improve this answer

























        up vote
        1
        down vote



        accepted







        up vote
        1
        down vote



        accepted






        You've hit one of the many issues with scanf. In this case scanf("%d %d", ...) is leaving a newline on the buffer. You can get it to slurp in trailing whitespace with a space on the end.



        scanf("%d %d ", &number_of_strings , &length_of_string); 


        Then how you're reading a line is complicated. You can simplify it like so:



         int c, j;
        for(j = 0; (c = getchar()) != 'n'; j++ ) {
        s[i][j] = (char)c;
        }
        s[i][j] = '';


        Or even simpler...



        for(int i=0 ; i<number_of_strings ; i++) {
        scanf("%29s", s[i]);
        }


        And there's no need for length_of_string. In fact, it's a liability since you've only allocated 30 bytes max. Similarly, number_of_strings can be higher than the allocated 20. It's better to read until input or memory is exhausted.



        #include <stdio.h>

        const int MAX_STRINGS = 20;
        const int MAX_LENGTH = 30;
        int main(){
        char s[MAX_STRINGS][MAX_LENGTH];
        int num_strings;
        for(num_strings = 0; num_strings < MAX_STRINGS ; num_strings++) {
        if( scanf("%29s", s[num_strings]) < 1 ) {
        break;
        }
        }

        for( int i = 0 ; i < num_strings; i++){
        printf("i= %d %sn",i,s[i]);
        }

        return 0;
        }





        share|improve this answer














        You've hit one of the many issues with scanf. In this case scanf("%d %d", ...) is leaving a newline on the buffer. You can get it to slurp in trailing whitespace with a space on the end.



        scanf("%d %d ", &number_of_strings , &length_of_string); 


        Then how you're reading a line is complicated. You can simplify it like so:



         int c, j;
        for(j = 0; (c = getchar()) != 'n'; j++ ) {
        s[i][j] = (char)c;
        }
        s[i][j] = '';


        Or even simpler...



        for(int i=0 ; i<number_of_strings ; i++) {
        scanf("%29s", s[i]);
        }


        And there's no need for length_of_string. In fact, it's a liability since you've only allocated 30 bytes max. Similarly, number_of_strings can be higher than the allocated 20. It's better to read until input or memory is exhausted.



        #include <stdio.h>

        const int MAX_STRINGS = 20;
        const int MAX_LENGTH = 30;
        int main(){
        char s[MAX_STRINGS][MAX_LENGTH];
        int num_strings;
        for(num_strings = 0; num_strings < MAX_STRINGS ; num_strings++) {
        if( scanf("%29s", s[num_strings]) < 1 ) {
        break;
        }
        }

        for( int i = 0 ; i < num_strings; i++){
        printf("i= %d %sn",i,s[i]);
        }

        return 0;
        }






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 12 at 8:17

























        answered Nov 12 at 8:09









        Schwern

        87.9k16101229




        87.9k16101229






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53257910%2f2d-array-giving-wrong-output%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Xamarin.iOS Cant Deploy on Iphone

            Glorious Revolution

            Dulmage-Mendelsohn matrix decomposition in Python