/* Covers some of the basics of strings, especially about the string terminating character '\0' = 0. */ #include #include /* contains character functions, such isuppper, tolower */ #include void chop(char*); /* When passed to a function, the pointer type char* is the same as the array type char[]. */ void main(){ char cc, text[70], pet[4], *d, w[4]; int occupied, reserved; strcpy(text,"A string constant."); /* cannot say text = "A string constant." (except as initialization)*/ occupied = strlen(text); reserved = sizeof(text)/sizeof(char); cout << "occupied = " << occupied << ", reserved = " << reserved << ".\n"; if (isupper(text[0])) cc=tolower(text[0]); cout << text << endl << cc << endl; /* If the first character is uppercase, the next statement changes it to its lowercase version. */ if (isupper(text[0])) text[0]=tolower(text[0]); cout << text << endl; chop(text); cout << text << endl; text[1]='?'; cout << text << endl; chop(text); cout << text << endl; pet[0]='c'; pet[1]='a'; pet[2]='t'; pet[3]=0; /* '/0'==0 */ cout << pet << endl; d = pet; /* this is OK since d is a pointer, not an array */ cout << d << endl; strcpy(w,pet); /* w=pet is not allowed. must use the function strcpy from cstring.h */ cout << w << endl; } /* takes a string and replaces the first bit of white space (either ' ' or '\n') with the string terminating character '\0' */ void chop (char* a){ int i=0; while (1){ // infinite loop if (a[i]==' ' || a[i]=='\n') a[i]='\0'; if (a[i]=='\0') return; i++; } }