CSCI1190: Beginning C Programming for Engineers - PowerPoint PPT Presentation

1 / 9
About This Presentation
Title:

CSCI1190: Beginning C Programming for Engineers

Description:

Characters are small integers (0-255) Character constants are integers that denote corresponding characters '0','1','A','B','a','b','n' ... – PowerPoint PPT presentation

Number of Views:24
Avg rating:3.0/5.0
Slides: 10
Provided by: CSU98
Category:

less

Transcript and Presenter's Notes

Title: CSCI1190: Beginning C Programming for Engineers


1
CSCI-1190 Beginning C Programming for Engineers
  • Lecture 5 Characters and Strings
  • Gang Chen

2
Characters
  • Type char
  • Characters are small integers (0-255)
  • Character constants are integers that denote
    corresponding characters
  • '0','1','A','B','a','b','\n'
  • ASCII code maps characters to integers

3
ASCII Code
4
Strings
  • Two interpretations
  • Arrays whose elements are characters
  • Pointers pointing to characters
  • Strings are always terminated with a NULL
    character ('\0' or 0)
  • char a"hello\n" / size? /
  • char bhello\n

a0
a1
a2
a3
a4
a5
a6
b
(b1)
(b2)
(b3)
(b4)
(b5)
(b6)
o
l
l
e
h
\n
null
111
108
108
101
104
10
0
5
Input/Output with Strings
  • include ltstdio.hgt
  • int main()
  • char s10
  • scanf("s",s) / bad /
  • scanf("9s",s) / good /
  • printf("s",s)
  • return 0

6
String Operations
  • The header file string.h contains functions that
    work with strings
  • strlen(a) number of characters in a
  • strcmp(a,b) compares a and b, returning 0 if
    they are equal
  • NOT ab
  • strcpy(a,b) copies contents of b into a
  • NOT ab

7
In-Class Exercise 5-1
  • Write a program that reads a line of text from
    the keyboard using the gets() funtion, then
    prints it out backwards. For instance, if you
    type in the line
  • Test data
  • The result should be
  • atad tseT
  • The syntax for the gets() function
  • char s100
  • gets(s)
  • Make use of the strlen() function

8
Converting Numeric Strings to Numbers
  • From characters to digits
  • / a is a character /
  • na-'0' / n is now a digit /
  • From digits to numbers
  • 3492 2910410031000
  • 210(910(4103))

9
In-Class Exercise 5-2
  • Write a program that reads an integer represented
    as a string from the keyboard, then coverts the
    string to the integer and prints it out.
  • Notes
  • You must use scanf("s",s) to read a string
  • Do NOT use atoi() or any other similar functions
Write a Comment
User Comments (0)
About PowerShow.com