Declare and I/O

Standard Input/Output
  • Strings

    • String is a sequence of characters
    • In C, there is no built-in data type for strings
    • String can be represented as an array of characters
    • String should always have a NULL character (‘\0’) at the end, to present the end of string.
    • String constants can be assigned to character array variables
      • String constants are always enclosed within double quotes (“”)
  • Input Strings

    • You can use gets or scanf functions to read inputs for strings
    • Example, a variable name is declared as
      • char name[10];
    • Then you could get name from input as
      • scanf("%s", name); //get name terminated by space
      • scanf("%[^\n]s", name);//get name including spaces
      • gets(name);//get name including spaces
  • Illegal operations on Strings

    • C does not allow one array to be assigned to another, thus statements of following forms are illegal
    • Assignment is not allowed
      • name=“Good” or name1 = name;
    • Concatenation is not allowed
      • name = name + “ to C“;
    • Comparing two strings is not allowed
      • if(name1==name){…}
  • StringDemo Source Code

    /*

     * File:   main.c

     * Author: phamvanvung

     *

     * Created on September 21, 2014, 4:42 PM

     */

     

    #include <stdio.h>

    #include <stdlib.h>

     

    /*

     *

     */

    int main(int argc, char** argv) {

        //char name[10]= "Mr. A";

        //printf("Welcome %s to String tutorial!", name);

        char name[10];

        printf("Please input your name: ");

        //    gets(name);

        //    puts("Welcome");

        //    puts(name);

        //    puts("to String tutorial!");

        scanf("%[^\n]s", name);

        printf("Welcome %s to String tutorial!", name);

        return (EXIT_SUCCESS);

    }