Searching for a string in a file in C++
In C language, a string is stored in an array of char characters, the char type can store a letter (we said only one letter and no more). It can also store numbers between -128 and 127.Since the computer only understands numbers, letters are transformed into numbers. So each character is associated with a number. The C language does this very quickly. e.g.:
The character 'a' corresponds in the ASCII code to the number 97. To check, type alt+97.
char letter = ' to ';
printf("%c\n", letter);
Page Channel is an array of type char:
char string[]="I'm a programmer";
Our goal is to read from a text file and find out if a text file is available. string is in this file. We have a file in the Directory "C:/test.txt", c file contains text, for example a simple sentence:my name is X and I'm a programmer.
In C, char channel[] is represented as follows:
j | e | s | u | i | s | u | n | p | r | o | g | r | a | m | m | e | u | r | '\0' |
' \0 ' indicates the end of the array.
#include < iostream>
#include < fstream>
#include < string>
#include < sstream>
using namespace std;
void searchInFile(char string[])
{
ifstream myStream("C:/test.txt");
if(myFlow)
{
int i=0,position=0;
//The reading is done per character
myFlux.clear();
//initialize the playhead of 0
//ios::beg: start from start
myFlux.seekg(0, ios::beg);
char c;
//as long as it's not the end of the file
while(myStream.get(c))
{
//increment the position of the playhead
position++;
//if the character matches the character of the
//string you are looking for in the i
//then move to the next character
if(c==string[i]){
i++;
//if all the characters in the string are
//checked, then we found the string in
//the file
if(i==strlen(string)) //strlen: returns the length of the string
printf("The searched string is in the position: %d "
" and ends at the position %d\n, position-strlen(string),position);
}
//otherwise if we find a single character
//that doesn't match then
//restart from 0
else
i=0;
}
}
else
printf("Unable to open file\n");
}
int main()
{
char string[]="a programmer";
searchFile(string);
system("pause");
}