problem

how to read specific char like "and" from .txt file?
myfile:
hello who are you ,and where did you come from?
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <fstream>
using namespace std;
int main(){
ifstream myfile;
myfile.open("file.txt");
string string1,string2;
getline(myfile,string1,',');
getline(myfile,string2,',');
myfile.close();
cout<<string2<<endl;
return 0;}

Last edited on
its not your concern but I am still not understood
Probably you did not explain well what you want... What does "read specific char from a file" mean?
1. you want to verifiy if a word (like "and") is written in a file
2. you want to find at which position is the first/last occurrence of the word
3. you want ...

Try to be as precise as you can, otherwise helping you is very difficult!
I want read the whole file to search a word like "read" or "what" if they exist in file I want to save them in a string want to print that word. Now I think it us clear. I hope.
Ok, so now that we all understand the problem, it is quite easy to give an answer:

- read the file line by line
- split every line at common separators (spaces, dots, commas, colons, semi-colons, ...)
- store each word in a std::vector<std::string>

When you have finished, you have a vector which contains every word in the file. Now you simply have to scan the vector and search for the word you want.

In order to split a string in words, you can use a function like this

1
2
3
4
5
6
7
void split(const std::string &s, char delim, std::vector<std::string> &elems) {
	std::stringstream ss(s);
	std::string item;
	while (std::getline(ss, item, delim)) {
		elems.push_back(item);
	}
}


Of course you have to modify it a little bit to include more separators, but it shouldn't be too difficult.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <fstream>
using namespace std;

int main()
{
    string search = "what";
    fstream input("textFile.txt");
    string test;

    while(input>>test)
   {
        if(test == search)
        //do what you want with it.
    }
   
   input.close();
   return 0;
}

they exist in file I want to save them
Has you search word not already been saved in search before even being found in the file?
thank you.
Topic archived. No new replies allowed.