GoConqr has a new look! Let us know what you think.

Notes

Strings in C: char arrays, scanf, fgets and sprintf

Alina Kozham English 11 pages

Content of the notes (11)

Page 1

Strings

In C there is no string

"" double quote for string;

String is an array of char ending with null is ('\0');

a character pointer:

char *myString="Hello"; // string as a char pointer

a character array:

char myString[]="Hello"; // string as a chat in an array

char myString[]={'h', 'e', 'l', 'l ', 'o', '\0'}; // '\0' shows that it is a string, without it will be just a string

scanf("%19s", myArray); // 19 is needed just ti be safe. so only 19 characters can be read.

one place is for terminating character

no address operator &, because the name of the array is already address

it does not include white spaces;

scanf can read one character, but wont read a text/sentence/line;

reads string until the space/tab/new line;

sprintf - you printf something in your string, not on the screen

int sprintf(char *s, const char *format,...);

sscanf() - reads from a string

fgets() - (array name, length, reads from what)

putchar - to print a line we need to know how ling it is

Page 2

strings and chars cont'd

Character I/O:

input: scanf - &c;

char c;

scanf("%c", &c);

input : getchar();

c = getchar();

output: putchar(c);

output: printf("c", c);

FUCNTIONS LIKE ISDIGIT ISALPHA ISALNUM ISUPPER ISLOWER WILL BE IN THE EXAM

STRINGS

- a series of characters;

-included in "" double quote

"A" is a stirng;

'A' is a character;

- ***. string is ended by terminating null;

-null = '\0'

- can be defined:

- pointer: *p = "hello";

-array: string[10] ="hello";

- the difference between: If you want to change the value YOU NEED TO DEFINE IT AS AN ARRAY;

- string I/O:

input: scanf - %s;

char string [100];

scanf("%99s", string); // you need to show size here. size is 99 because onme place is for termintating symbol

input - fgets - read line from a file

fgets(string 100, stdin); // stdin - keybord

the difference is SCANF IS FOR READ A READ - KEEPS READING UNTIL SPACE;

THE DIFFERENCE BETWEEN IS FGETS - KEEP READING UNTIL A NEW LINE;

output: printf("%s","this is an example");

output - puts - print a line of text;

READ/PRINT FROM/TO STRING: sscanf, sprintf;

char string[80];

sscanf - read from a string

sscanf (string, "%d%d",&x, &y);

" 5 8" - x = 5, y = 8;

sprintf - print to a string;

sprintf(string, "%d %f", x ,d);

Page 3

structure

-you can display a set of info

-can display different data types in one array

- in data base we cal it - a field

- Example: student information

struct studentInfo{ // the name of the data type

int id;

int age;

char name[20];

char gender;

double gpa;

}; // do not forget this semicolon

- struct strucruteTag {type memberName.....};

-structure tag is optional

-members in one structure name should unique;

-the member of the structure can be another structure;

-however the member of the structure cant be itself

-you can point a pointer to the same type(self-referential)

- you cant gave the default value in member definition ;

-you cant compare two structure type

- because value in holes is different

- for alignment we escape 3 bytes

-

-if you have a function with structure parameter - passing by value

Page 4

TYPEDEF

-gives type another name

- does not create new type

-an alias of existing type

- typedef double real// real is an alias of double

typedef struct course Course // Course is an alias

-mostly used to define a type of structure, because it is awkward to define structure

quiz 3 - character and string

-1 hour

two parts:

- theory : T/F, MC, 4 - filling ques

-practice: 20 marks + 4 bonus marks

quiz 4 - strucrue and file

quiz 5 - other topics

Page 5

UNION

- all members share the same memory space;

-the size of union is at least the max size of the member

Page 6

ENUMERATION

- a set of const integers;

-type:

-enum days(mon,tue,wed,thu,fri,sat,sun);

- all capitalized

-name must be unique, but the value can be the same

-by default the first one is 0 and then it increments by 1;

Page 7

FILE PROCESSING

1. File

- permanent storage of data;

-standard files: stdin. stdout, stderr

-***. directly use them without opening them

-stream of bytes

-text files: for human; binary files: for machine;

-sequential and random accessing

2. Text I/O sequential accessing

- step 1: open the file

-FILE *filePtr;

filePtr = fopen("example.txt", "mode");

if (filePtr == NULL){

puts("Cant open the file");// not required but highly recommended

}

"mode"

basic modes: r - reading, w - writing, a - appending;

file exists ***.w - content will be discarded- will be clean up

updating mode: "+", r+/w+/a+ : reading/writing;

binary mode: "b", rb/wb/ab, rb+/wb+/ab+

//find the file ("G:\\example.txt") - to find th e file give the full path

- step 2: do the reading or writing

- character I/O: fgetc/fputc (getchar/putchar);

-string I/O: fgets, fputs (gets/puts) ;

- fgets(string, n, stdin);

fgets(string,n, stdin) ; // reading from the keyboard;

-formated I/O: fscanf/ fprintf

fscanf(filePtr, ...);

fprintf(filePtr, ....);

fcanf(srdin, ....) == scanf(..);

fprintf(stdout, ...)==printf(..);

feof(filePtr) // test whether there any more data or not

- step 3: close the file

-fclose (filePtr)

FILE POSITION POINTER

-ACTUALLY NOT A REAL POINTER

- A REAL POINTER IS A MEMORY ADDRESS

-THE OFFSET OF THE CURRENT POSITION FROM THE BEGInNING in terms of the number of bytes

rewind(filePtr); //move pointer to the beginning

3. Binary I/O

Page 8

Минусы text I/O:

- ты можешь читать только сначала, а не с любого места которого хочешь

-тяжелее обновить файл

Page 9

Page 10

ФИНАЛКА

- будут, в основном, вопросы по темам после мидки

-но! прердыдущие темы тоже будут

-preprocessor and data structure тоже будут(последние темы)

PREPROCESSOR

#include

-directives

-include copy of a file into your program

- enum, constants, struct definition, function prototypes(those are incliuded in the header file)

1. #include

- compiler will search the header file from system folder

2. #include "myheader.h"

- compiler will search from the place where you have your source code

#define

1. symbolic constants (constant is the value)

-#define ARRAYSIZE 100

-int myarray[ARRAYSIZE]

const double PI= 3.14566; //define a constant

-const are in uppercase

2.Macros - operations (preferable function)

-for very small operations;

- takes no argument

-just does the replacement, the same as symbolic const

-takes arguments

#define CIRCLE_AREA(x) (PI*x*x)

#define SUM(x,y) x+y

-*****. put every argument into parenthesis ()

#define CIRCLE_AREA(x) (PI*(x)*(x))

#define SUM(x,y) ((x)+(y))

- no space between the name of the macro and the arg

#define CIRCLE_AREA_(x) (PI*(x)*(x))

CIRCLE_AREA(3.4); // expanded to PI* 3.4*3.4

SUM(3,4); //expanded 3+4

CIRCLE_AREA(a+b)

//without () will expanded like this PI*a+b*a+b

//but we expect smthn like this PI*(a+b)*(a+b)

CONDITIONAL COMPILATION

- need in the debugging

#ifdef TRUE

#undef TRUE

#define TRUE 1

#endif

ELSE

#error 1-should not be here

# - used to convert the token to a string

- #token -"token" becomes a string

-#define HELLO(x) printf (#x) // convert an arg to a string

...

HELLO(hello);// printf ("hello");

## - connect (concatenate) two tokens together

- #define CONCAT(x,y) x##y

.... CONCAT (o,k) = ok //will output OK

- NO QUESTIONS ABOUT THIS

#line 100 - helps to debug the code

- you just redefine line number everywhere you want

- so that your first line may start in the middle of your function

ASSERTION

- for debugging process

- #include

Page 11

structer cannot have the member of itself

itself cannot be the type of structure itself

byt we can use pointer to do that

this structure called self-referential structures

Information

Description
Note on Untitled, created by Alina Kozham on 01/11/2018.
Created by
Alina Kozham · Nov 2018
Updated
Dec 11, 2018
Views
3
Rating

Feedback

What is it about?

What do you think of the new look?

How do you like it?