String and Text File
Inst. Nguyễn Minh Huy
Fundamentals of Programming - Nguyễn Minh Huy 1
Contents
String.
Text file.
Fundamentals of Programming - Nguyễn Minh Huy 2
String
Basic concept:
String is an array of chars storing readable text.
C string (null-
(null-terminated string):
Array of chars + ‘\
‘\0’ at the end.
Declaration: char <string name> [ <string length> + 1 ];
0 1 2 3 4 5
char s1[ 5 ];
]; s1 ? ? ? ? \0
char s2[ ] {“hello”}
{“hello”};; s2 h e l l o \0
C++ string (std::string):
Data type in library <string>.
Support dynamic string.
Declaration: std::string <string name>;
name>;
Fundamentals of Programming - Nguyễn Minh Huy 3
String
Basic concept:
String comes with helpful libraries:
C: <string.h
<string.h>,
>, <
<stdio.h
stdio.h>,
>, <
<ctype.h
ctype.h>.
>.
C++: <string>, <iostream
<iostream>,>, <
<sstream
sstream>.
>.
Iterate string:
C string: check for ‘\
‘\0’ or use strlen
strlen(<string>).
(<string>).
for (int
(int i = 0; s[ i ] != ‘\
‘\0’
0’;; ++i
++i)
{
// Process character s[ i ].
}
std::string: <string>.length().
for (int
(int i = 0; i < [Link]()
[Link]();; ++i
++i)
{
// Process character s[ i ].
}
Fundamentals of Programming - Nguyễn Minh Huy 4
String
Input string:
C string:
fgets( <string>, <max length>, stdin ).
fgets(
std::[Link]
std:: [Link](( <string>, <max length> ) (C++).
std::string:
std::getline
std:: getline(( std::cin
std::cin,, <string> ).
Output string:
C string:
printf( “%s”, <string> ).
printf(
puts( <string> ).
std::cout
std:: cout << <string> (C++).
std::string: std::cout
std::cout << <string>.
Fundamentals of Programming - Nguyễn Minh Huy 5
String
Practice: <ctype.h
<ctype.h>>
Count words: “the quick fox” 3 words.
Space: ‘ ‘, ‘\‘\t’, ‘\
‘\n’, ‘\
‘\r’ -> isspace
isspace(<char>).
(<char>).
Alphabet: ‘A’‘A’––‘Z’, ‘‘a’
a’--‘z
‘z’’ -> isalpha
isalpha(<char>).
(<char>).
Punctuation: ‘.‘, ‘,’, ‘?’, ‘!’,… -> ispunct
ispunct(<char>).
(<char>).
Digit: ‘0’, ‘1’, ‘2’, ‘3’, ‘4’, … -> isdigit
isdigit(<char>).
(<char>).
Capitalize words: “the quick fox” “The Quick Fox”.
Lower alphabet: ‘a’
a’--‘z
‘z’’ -> islower
islower(<char>).
(<char>).
Capitalize: <char> - 32 -> toupper
toupper(<char>).
(<char>).
Fundamentals of Programming - Nguyễn Minh Huy 6
Contents
String.
String.
Text file.
Fundamentals of Programming - Nguyễn Minh Huy 7
Text file
File IO:
Advantages (vs. keyboard and screen):
Do not need user:
Automatic control..
Repeatable.
Communicate with other programs.
Persistent storage.
Disadvantages (vs. RAM):
Sequential vs. random access.
Slower.
Fundamentals of Programming - Nguyễn Minh Huy 8
Text file
File stream:
File is either input or output device.
File stream is connection between program and file.
Declaration:
C (library <stdio.h
<stdio.h>):
>): FILE *<name>.
*<name>.
C++ (library <fstream
<fstream>):>): std::
std::fstream
fstream <name>.
Steps to process a file:
Open file stream.
Read/write file stream.
Close file stream.
Fundamentals of Programming - Nguyễn Minh Huy 9
Text file
Open file stream:
C syntax:
fopen(“<file path>”, “<open mode>”)
fopen( mode>”);
Return: file stream (succeeded) or NULL (error).
FILE *f = fopenfopen((“C:/[Link]”, “r“r”);
if ( !f ) fprintf
fprintf((stderr
stderr,, “Error.”);
else printf
printf(“Succeeded.”);
(“Succeeded.”);
C++ syntax:
<stream>(“<file path>”, <C++ open mode>)
<stream>(“<file mode>);
Check <stream> to know the result.
std::fstream f ((“[Link]”,
std::fstream “[Link]”, std::
std::ios
ios::in)
::in);;
if ( !f ) std::cerr
std::cerr << “Error.”;
else std::cout
std::cout << “Succeeded.”;
Fundamentals of Programming - Nguyễn Minh Huy 10
Text file
Open file stream:
C/C++ open modes:
Open mode C/C++ Ý nghĩa
r / std::ios::in Read-only, open for reading (text mode).
Return NULL if file not found.
w / std::ios:out Write-only, open for writing (text mode).
File created or overwritten.
a / std::ios:app Append-only, open for append (text mode).
File created if not found.
[r/w/a]+ / combine | Combine read and write (text mode).
[r/w/a]b / combine | Read and write in binary (binary mode).
Fundamentals of Programming - Nguyễn Minh Huy 11
Text file
Close file stream:
C syntax:
fclose(<stream>
fclose( <stream>));
Close an opened stream.
Always close a stream after used.
FILE *f = fopen
fopen((“C:
“C:\\\[Link]”, “r
“r”);
if ( !f ) {
fprintf((stderr,
fprintf stderr, “Error.”);
fclose(( f );
fclose // Wrong.
} else {
printf(“Succeeded.”);
printf (“Succeeded.”);
fclose(( f );
fclose // Right.
}
C++ syntax: <stream>.close(
<stream>.close( );
);
Fundamentals of Programming - Nguyễn Minh Huy 12
Text file
Read stream:
C syntax:
fscanf(<stream>, “<type format>”, &<var
fscanf( &<var 1>, …
…));
fgets((<string>, <max line>, <stream>)
fgets <stream>);
FILE *f = fopen
fopen((“C:
“C:\\\[Link]”, “r
“r”);
if ( !f ) fprintf
fprintf((stderr
stderr,, “Error.”);
else {
int a, b;
b; char s [ 100 ];
fscanf(( f, “%d %d”, &a, &b );
fscanf
fgets(( s
fgets s,, 100, f );
fclose(( f );
fclose
}
C++ syntax:
<stream> >> <var>.
var>.
<stream>.getline
<stream>. getline(( <string>, <max line> ).
Fundamentals of Programming - Nguyễn Minh Huy 13
Text file
Write stream:
C syntax:
fprintf((<File stream>, “<Định
fprintf “<Định dạng kiểu
kiểu>”,
>”, <
<Biến
Biến 1>, …
…));
FILE *f = fopen
fopen((“C:“C:\\\[Link]”, “w
“w”);
if ( !f ) fprintf(
fprintf(stderr,
stderr, “Error.”);
else {
int a = 12;
float b = 4.165;
char c = ‘A’;
fprintf(( f, ““Gia
fprintf Gia tri = %d %f %c”, a, b, c );
fclose(( f );
fclose
}
C++ syntax: <stream> << <var>.
var>.
Fundamentals of Programming - Nguyễn Minh Huy 14
Text file
File management:
Delete file:
Syntax: remove(
remove(“<file
“<file path>”)
path>”);
Return: 0 (succeeded), -1 (error).
Do not need file stream.
if ((remove(
remove(“C: “C:\\\[Link]”)
[Link]”) == 0)
printf(“File
printf (“File deleted.
deleted.\\n”);
else
printf(“Error:
printf (“Error: cannot delete file.
file.\\n”);
Fundamentals of Programming - Nguyễn Minh Huy 15
Text file
File management:
Rename/move file:
Syntax: rename(
rename(“<file
“<file path>”, “<new file path>”)
path>”);
Return: 0 (succeeded), -1 (error).
Both path must be in the same drive.
Do not need file stream.
if ((rename(
rename(“C:/[Link]”,
“C:/[Link]”, “C:/folder\
“C:/folder\\[Link]”)
[Link]”) == 0)
printf(“Succeeded.
printf (“Succeeded.\\n”);
else
printf(“Error.
printf (“Error.\\n”);
Fundamentals of Programming - Nguyễn Minh Huy 16
Summary
String:
C string:
Array of chars + ‘\
‘\0’ at the end.
Null terminated string.
C++ string (std::string):
A data type in library <string>.
Dynamic string.
Input/output:
C string: fgets,
fgets, std::[Link]
std::[Link],, printf
printf,, std::
std::cout
cout..
std::string: std::getline
std::getline,, std::
std::cout
cout..
<ctype.h>:
ctype.h>: support checking character.
Fundamentals of Programming - Nguyễn Minh Huy 17
Summary
Text file:
File stream: connection between program and file.
C file stream: FILE * (<stdio.h
(<stdio.h>).
>).
Open/close: fopen
fopen,, fclose.
fclose.
Read/write: fscanf
fscanf,, fprintf,
fprintf, fgets.
fgets.
C++ file stream: std::fstream
std::fstream (<
(<fstream
fstream>).
>).
Open/close: <stream>(), <stream>.close.
Read/write: <stream> >>, <<, <stream>.getline
<stream>.getline..
Fundamentals of Programming - Nguyễn Minh Huy 18
Summary
Text file:
File stream: connection between program and file.
C file stream: FILE * (<stdio.h
(<stdio.h>).
>).
Open/close: fopen
fopen,, fclose.
fclose.
Read/write: fscanf
fscanf,, fprintf,
fprintf, fgets.
fgets.
C++ file stream: std::fstream
std::fstream (<
(<fstream
fstream>).
>).
Open/close: <stream>(), <stream>.close.
Read/write: <stream> >>, <<, <stream>.getline
<stream>.getline..
Fundamentals of Programming - Nguyễn Minh Huy 19
Practice
Practice 6.1:
Write C/C++ program to trim spaces:
- Enter a sentence of words.
- Delete leading spaces at the beginning (trim left).
- Delete trailing spaces at the end (trim right).
- Delete duplicate spaces between words (keep one space).
Input format:
Enter a sentence = “ today is a beautiful day ”
Output format:
“today is a beautiful day”
Fundamentals of Programming - Nguyễn Minh Huy 20
Practice
Practice 6.2:
Write C/C++ program as follow:
- Enter a string S.
- Count frequencies of each character in S.
- Print the frequencies in descending order.
Input format:
S = tick tak tok
Output format:
3: k t
1: a c i o
Fundamentals of Programming - Nguyễn Minh Huy 21
Practice
Practice 6.3:
File [Link] stores a matrix of M x N integers:
- First line: M N (integers, rows and columns).
- Next M lines, line i stores N elements at row i of matrix.
Write C/C++ program to:
- Read matrix from [Link].
- Rotate left the matrix.
- Write the result to [Link] (same format as [Link]).
[Link] [Link]
23 32
123 36
456 25
14
Fundamentals of Programming - Nguyễn Minh Huy 22
Practice
Practice 6.4:
File [Link] stores sequence of integers separated by space.
Write C/C++ program as follow:
- Read sequence of integers from [Link].
- Extract prime numbers from the sequence.
- Write result to [Link] (same format as [Link]).
[Link]
5 1 2 9 46 23 11 39 43 117 20
[Link]
5 2 23 43 117
Fundamentals of Programming - Nguyễn Minh Huy 23
Practice
Practice 6.5:
File [Link] stores a list of arithmetic operations, each
operation is on a line containing an operator (character +, -, *, /) in
between two operands (integers).
Write C/C++ program as follow:
- Read list of operations from [Link].
- Compute the result of each operation.
- Write operation results to [Link].
[Link] [Link]
12 + 5 17
2 * 31 62
3/0 Divided by zero
60 / 2 30
7 – 20 -13
Fundamentals of Programming - Nguyễn Minh Huy 24
Practice
Practice 6.6:
File [Link] stores a list of students, each student is on 2 lines:
- First line format: student name|student id.
- Second line format: student points (floats) separated by spaces.
Write C/C++ program as follow:
- Read student list from [Link].
- For each student, capitalize student name and compute GPA.
- Write the result to [Link] in descending order of GPA.
[Link] [Link]
nguyen van a|24127001 24127002|Tran Thi B|7.6
8.5 6.0 7.5 24127001|Nguyen Van A|7.3
tran thi b|24127002
9.0 8.0 6.5 7.5
Fundamentals of Programming - Nguyễn Minh Huy 25
Practice
Practice 6.7:
Write C/C++ program to count words and numbers:
- Read from a text file [Link].
- Count and print the number of words and numbers in the file.
Notes:
- A word is a sequence of alphabets.
- A number is a sequence of digits.
[Link]
-----The,
----- The, quick ##123 fox,,, 456!!!
Screen output:
Word count: 3.
Number count: 2.
Fundamentals of Programming - Nguyễn Minh Huy 26