-1

In this program I have taken a dimensional character array of size[3][4], as long as I enter a 3 characters for each row it will work well.

For example: if I enter abc abd abd I get the same output but if i enter more letters in the first or second or 3rd row I get an error.

How should I check for null character in 2 dimensional?

# include <stdio.h>         
#include  <conio.h>   
# include <ctype.h>

void main()
{
   int i=0; 
   char name[3][4];
   printf("\n enter the names \n");
   for(i=0;i<3;i++)
   {
      scanf( "%s",name[i]); 
   } 

   printf( "you entered these names\n");
   for(i=0;i<3;i++)
   {
      printf( "%s\n",name[i]);
   }
   getch(); 
}
SHR
  • 7,940
  • 9
  • 38
  • 57
venkat
  • 43
  • 1
  • 1
  • 5

4 Answers4

5

As pointed out by @SouravGhosh, you can limit your scanf with "%3s", but the problem is still there if you don't flush stdin on each iteration.

You can do this:

printf("\n enter the names \n"); 
for(i = 0; i < 3; i++) {
    int c;
    scanf("%3s", name[i]);
    while ((c = fgetc(stdin)) != '\n' && c != EOF); /* Flush stdin */
}
Neuron
  • 5,141
  • 5
  • 38
  • 59
David Ranieri
  • 39,972
  • 7
  • 52
  • 94
3

How should I chk for null character in 2 dimensional ... [something has eaten the rest part, I guess]

You don't need to, at least not in current context.

The problem is in your approach of allocating memory and putting input into it. Your code has

char name[3][4];

if you enter more that three chars, you'll be overwriting the boundary of allocated memory [considering the space of \0]. You've to limit your scanf() using

scanf("%3s",name[i]);

Note:

  • change void main() to int main(). add a return 0 at the end.
  • always check the return value of scanf() to ensure proper input.

EDIT:

As for the logical part, you need to eat up the remainings of the input words to start scanning from the beginning of the next word.

Check the below code [Under Linux, so removed conio.h and getch()]

# include <stdio.h>
# include <ctype.h>
int main()
{
        int i=0; char name[3][4];
        int c = 0;
        printf("\n enter the names \n");
        for(i=0;i < 3;i++)
        {
                scanf( "%3s",name[i]);
                while(1)   // loop to eat up the rest of unwanted input
                {          // upto a ' ' or `\n` or `EOF`, whichever is earlier
                    c = getchar();
                    if (c == ' ' || c == '\n' || c == EOF) break;
                }
        }
        printf( "you entered these names\n");

        for(i=0;i<3;i++)
        {
                printf( "%s\n",name[i]);
        }
    return 0;
}
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • I tried your code..but I am getting one more problem .If I type abcd in the first row and abcd in the second row and press enter i get the output as abc in the first row and d in the second row and abc in the last row the .I dont get an option to enter 3rd name – venkat Feb 03 '15 at 11:29
  • @venkat I know, the remaining part of the earlier word is being feeded to the next `scanf()`, right? – Sourav Ghosh Feb 03 '15 at 11:32
  • YES.BUT I DONT WANT THAT IF I ENTER ABCD IN THE FIRST ROW HIJKL IN THE SECOND ROW AND XYZRE IN THE THIRD ROW I WANT TO GET ABC IN THE FIRST HIJ IN THE SECOND AND XYZ IN THE LAST – venkat Feb 03 '15 at 11:38
  • 2
    @venkat Please don't shout. – Sourav Ghosh Feb 03 '15 at 11:38
  • @venkat check my updated answer, the logic is there. – Sourav Ghosh Feb 03 '15 at 11:38
  • SIR, WHEN DID I SHOUT – venkat Feb 03 '15 at 11:40
  • @venkat writing in ALL CAPS is considered as shouting [and some people may think it as _rude_]. :-) – Sourav Ghosh Feb 03 '15 at 11:41
  • @venkat btw, did you try the latest approach which i provided? – Sourav Ghosh Feb 03 '15 at 11:41
  • problem solved I used the logic provided by Alter Mann. – venkat Feb 03 '15 at 11:50
  • Yes, it should be. :-) after all, my logic is a small variation of the logic used by Mr. @AlterMann . – Sourav Ghosh Feb 03 '15 at 11:55
  • @SouravGhosh, true, in fact `getchar` is typically defined as `#define getchar() getc(stdin)` in ``, (but I would remove the `c == ' '` in the comparison in order to flush the whole extra characters) – David Ranieri Feb 03 '15 at 12:11
  • @AlterMann I agree to your point sir, but as per my logic, it will also work with a single line input of `sourav ghosh abcde` , right? – Sourav Ghosh Feb 03 '15 at 12:12
  • Well, as you know `scanf("%s")` stops scanning at the first whitespace, for this purpose I would use `scanf("%3s %3s %3s", ...);` instead of `for(i=0;i < 3;i++) scanf("%3s", ...);` – David Ranieri Feb 03 '15 at 12:16
0

(Cringing after reading the answers to date.)

First, state the problem clearly. You want to read a line from stdin, and extract three short whitespace separated strings. The stored strings are NUL terminated and at most three characters (excluding the NUL).

#include <stdio.h>         

void main(int, char**) {
    char name[3][4];
    printf("\n enter the names \n");
    {
        // Read tbe line of input text.
        char line[80];
        if (0 == fgets(line, sizeof(line), stdin)) {
            printf("Nothing read!\n");
            return 1;           
        } 
        int n_line = strlen(line);
        if ('\n' != line[n_line - 1]) {
            printf("Input too long!\n");
            return 2;
        }
        // Parse out the three values.
        int v = sscanf(line, "%3s %3s %3s", name[0], name[1], name[2]);
        if (3 != v) {
            printf("Too few values!\n");
            return 3;
        }
    }
    // We now have the three values, with errors checked.
    printf("you entered these names\n%s\n%s\n%s\n",
        name[0], name[1], name[2]
    );
    return 0;
}
0

you might consider something on the order of scanf( "%3s%*s",name[i]); which should, if I recall correctly, take the first three characters (up to a whitespace) into name, and then ignore anything else up to the next white space. This will cover your long entries and it does not care what the white space is.

This is not a perfect answer as it will probably eat the middle entry of A B C if single or double character entries are mode. strtok, will separate a line into useful bits and you can then take substrings of the bits into your name[] fields.

Perhaps figuring out the entire requirement before writing code would be the first step in the process.

Scott
  • 1