In-Class Practice

String Input


Consider the following programs

 int main(void)
 {
         char s[10] = "?";
         scanf("%s", s);
         return 0;
 }
 int main(void)
 {
         char s[10] = "?";
         scanf("%[^\n]", s);
         return 0;
 }
 int main(void)
 {
         char s[10] = "?";
         gets(s);
         return 0;
 }
 void getstr(char [], int);

 int main(void)
 {
         char s[10] = "?";
         getstr(s, 9);
         return 0;
 }
 
 void getstr(char s[], int max)
 {
         int i = 0, c;
         while((c = getchar()) != '\n'
          && c != EOF) 
                 if (i < max)
                         s[i++] = (char) c; 
         s[i] = '\0';
 }

Fill in the table below to show the data stored in s by each program along with the return code from scanf().  The quotes (" "'s) in the first column are bounds on the input that identify it, but are not entered by the user

User Inputscanf("%s", s)scanf("%[^\n]", s)getstr(s, 9)
"Hi, there"   
"Hello, there"   
""   

Compare your answers with those of one of your colleagues.  Make sure that you agree and understand all of the differences.


   Printer Friendly Version of this Page print this page     Top  Go Back to the Top of this Page



  Designed by Chris Szalwinski   Copying From This Site   

Creative Commons License