Compare variable with each line from a txt file - c++

I have to compare each line of a txt file with a user input variable.
If the userinput word exists within the txt file, it should prompt the user "The word exists." and if it does not, than exit the program.
This is what the text file looks like:
hello
hey
wow
your
Here is my code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
ifstream file("words.txt");
string content;
string userinput;
while(file >> content) {
cout << content << endl; // gets all the lines from the txt file
while(userinput != "exit") {
// asks user for input
cin >> userinput;
// compares two inputs
if (userinput == content)
{
cout << "The word exists." << endl;
} else {
break;
}
if (userinput == "exit") {
break;
}
}
}
return 0;
}
Its not working for me. I am able to return all the words from the txt file but not able to compare the userinput text with the txt lines from the txt file. Any help would be great. Thanks!
Updated code:
while(iFile >> content) {
while(userinput != "exit") {
// asks user for input
cin >> userinput;
// compares two inputs
if (content.find(userinput) != std::string::npos)
{
cout << "The word exists." << endl;
} else {
break;
}
if (userinput == "exit") {
break;
}
}
}
P.S: I am pretty new to c++. A student

#include <string>
#include <iostream>
#include <fstream>
#include <unordered_set>
using namespace std;
int main()
{
fstream file("wy.txt");
string line;
unordered_set<string> res;
while(file>>line)
{
res.insert(line);
}
do
{
cout<<"Please input the word: "<<endl;
string str;
cin>>str;
if (res.find(str) != res.end())
cout << "The word exists." << endl;
else
break;
} while (true);
}
This code can work fine.

You are running a loop over each line-token in the file, in which you ask the user for guesses until he gives up for each? Nice one, but not what you said.
What you want to do instead:
Read the file, parsing it into word-tokens which you save in an std::unordered_set.
Then ask the user which word shall be matched.
Ask the std::unordered_map to divulge its secrets.
Try it.

When you are writing:
// compares two inputs
if (userinput == content)
You are indeed checking if the user has entered the exact text in content. What you want is checking if userinput is contained in content:
// check if the userinput is found in the text
if(content.find(userinput) != std::string::npos)
You need also to read the complete file. Right now you are reading from the input file each time you are asking an input from the user.
#include <iostream>
#include <fstream>
#include <memory>
#include <sstream>
#include <sys/types.h>
#include <sys/stat.h>
inline static bool fileExists(const std::string& name) {
struct stat buffer;
return (stat (name.c_str(), &buffer) == 0);
}
/// Read the file content and return as a string
static std::string readFile(const std::string &filename)
{
std::ifstream t(filename);
std::stringstream buffer;
buffer << t.rdbuf();
return buffer.str();
}
int main() {
std::string filename("words.txt");
if(!fileExists(filename))
// print error
return -1;
string content = readFile(filename);
string userinput;
... // handle userinput from now
Note that this is inefficient. Since you text is always the same and you are repeating searches, it could be preprocessed. There are multiple data structure that can help. For instance you could have a hash map and populate it with each line as keys.

Related

replacing string based on user input c++

i want to receive an input from user and search a file for that input. when i found a line that includes that specific word, i want to print it and get another input to change a part of that line based on second user input with third user input. (I'm writing a hospital management app and this is a part of project that patients and edit their document).
i completed 90 percent of the project but i don't know how to replace it. check out following code:
#include <iostream>
#include <stream>
#include <string.h>
#include <string>
using namespace std;
int main(){
string srch;
string line;
fstream Myfile;
string word, replacement, name;
int counter;
Myfile.open("Patientlist.txt", ios::in|ios::out);
cout << "\nEnter your Name: ";
cin.ignore();
getline(cin, srch);
if(Myfile.is_open())
{
while(getline(Myfile, line)){
if (line.find(srch) != string::npos){
cout << "\nYour details are: \n" << line << endl << "What do you want to change? *type it's word and then type the replacement!*" << endl;
cin >> word >> replacement;
}
// i want to change in here
}
}else
{
cout << "\nSearch Failed... Patient not found!" << endl;
}
Myfile.close();
}
for example my file contains this line ( David , ha , 2002 ) and user wants to change 2002 to 2003
You cannot replace the string directly in the file. You have to:
Write to a temporary file what you read & changed.
Rename the original one (or delete it if you are sure everything went fine).
Rename the temporary file to the original one.
Ideally, the rename part should be done in one step. For instance, you do not want to end up with no file because the original file was deleted but the temporary one was not renamed due to some error - see your OS documentation for this.
Here's an idea:
#include <iostream>
#include <fstream>
#include <string>
#include <cstdio>
using namespace std;
void replace(string& s, const string& old_str, const string& new_str)
{
for (size_t off = 0, found_idx = s.find(old_str, off); found_idx != string::npos; off += new_str.length(), found_idx = s.find(old_str, off))
s.replace(found_idx, old_str.length(), new_str);
}
int main()
{
const char* in_fn = "c:/temp/in.txt";
const char* bak_fn = "c:/temp/in.bak";
const char* tmp_fn = "c:/temp/tmp.txt";
const char* out_fn = "c:/temp/out.txt";
string old_str{ "2002" };
string new_str{ "2003" };
// read, rename, write
{
ifstream in{ in_fn };
if (!in)
return -1; // could not open
ofstream tmp{ tmp_fn };
if (!tmp)
return -2; // could not open
string line;
while (getline(in, line))
{
replace(line, old_str, new_str);
tmp << line << endl;
}
} // in & tmp are closed here
// this should be done in one step
{
remove(bak_fn);
rename(in_fn, bak_fn);
remove(out_fn);
rename(tmp_fn, in_fn);
remove(tmp_fn);
}
return 0;
}
One possible way:
Close the file after you read it into "line" variable, then:
std::replace(0, line.length(), "2002", "2003")
Then overwrite the old file.
Note that std::replace is different from string::replace!!
The header is supposed to be <fstream> rather than <stream>
you can't read and write to a file simultaneously so I have closed the file after reading before reopening the file for writing.
instead of updating text inside the file, your line can be updated and then written to file.
#include <iostream>
#include <fstream>
#include <string.h>
#include <string>
using namespace std;
int main(){
string srch;
string line, line2;
fstream Myfile;
string word, replacement, name;
int counter;
Myfile.open("Patientlist.txt", ios::in);
cout << "\nEnter your Name: ";
cin.ignore();
getline(cin, srch);
if(Myfile.is_open())
{
while(getline(Myfile, line)){
if (line.find(srch) != string::npos){
cout << "\nYour details are: \n" << line << endl << "What do you want to change? *type it's word and then type the replacement!*" << endl;
cin >> word >> replacement;
int index = line.find(word);
if (index != string::npos){
Myfile.close();
Myfile.open("Patientlist.txt", ios::out);
line.replace(index, word.length(), replacement);
Myfile.write(line.data(), line.size());
Myfile.close();
}
}
// i want to change in here
}
}else
{
cout << "\nSearch Failed... Patient not found!" << endl;
}
}

Checking for username and password in sequence from a text file in C++

I haven't used fstreams much, so I'm a bit lost. I created a text file that has a list of random words that I wanted to use as a list of usernames and passwords for my program.
I want my program to check if the user exists (first string in the line), then check if the second word after it "matches".
So far I have this:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream inFile;
inFile.open("userData.txt");
// Check for error
if (inFile.fail()) {
cerr << "error opening file" << endl;
exit(1);
}
string user, pass;
int Count = 0;
// Read file till you reach the end and check for matchs
while (!inFile.eof()) {
inFile >> user >> pass;
if (user == "Banana", "Apple") {
Count++;
}
cout << Count << " users found!" << endl;
}
}
My text file contains:
Banana Apple /n
Carrot Strawberry /n
Chocolate Cake /n
Cheese Pie /n
I get my code is not good right now, but I don't really know what I'm doing.
Read below:
while (!inFile.eof()) {
inFile >> user >> pass;
if (user == "Banana", "Apple") {
Count++; // No point in doing so because this only happens once
}
cout << Count << " users found!" << endl;
}
Use while (inFile >> user >> pass){ instead of while (!inFile.eof()){. Why?
Try this instead:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream inFile;
inFile.open("userData.txt");
// Check for error
if (inFile.fail()) {
cerr << "error opening file" << endl;
exit(1);
}
string user, pass;
int Count = 0;
// Read file till you reach the end and check for matchs
while (inFile >> user >> pass) {
if (user == "Banana" && pass == "Apple") {
cout <<"user found!" << endl;
}
}
}

Searching text file for specific user-inputted string

I'm trying to write a program which opens a text file full of words (a "dictionary" minus the definitions) and stores these values in strings to compare them against a user input to determine whether the user input is spelled correctly.
I go the program to work and do what I wanted, but I can't seem to figure out one specific detail. I want the program to continue running until the user enters "exit" as an input. The only problem is that my program continues spewing out either "input is spelled correctly" or "input is not spelled correctly" ad infinitum without giving the user a chance to input more values in.
How do I make it so the program only outputs one of these two options only once and then prompts the user for another input instead of a never-ending stream of the same statement? Thank you in advanced!
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string line; //holds values from txt file
string input; //holds user-inputted values
ifstream inputFile; //fstream operator declaration
bool isFound = false; //bool value to indicate if the string has been found
inputFile.open("dict.txt", ios::in);
if (inputFile)
{
cout << "Enter word to spellcheck (or exit to end)\n";
getline(cin, input);
while (input != "exit")
{
while (getline(inputFile, line))
{
if (input == line)
{
isFound = true;
break;
}
else
{
isFound = false;
}
}
inputFile.close();
if (isFound)
{
cout << input << " is spelled correctly.\n";
}
else
{
cout << input << " is not spelled correctly.\n";
}
}
if (input == "exit")
{
cout << "Ending program...\n";
}
}
else
{
cout << "Cannot open file\n";
}
return 0;
}
Inside the body of the
while (input != "exit")
loop the user is never asked to update the value of input. Moving getline(cin, input) into the while condition like this:
while (getline(cin, input) && input != "exit")
will solve that problem.
Then next problem is the handling of the dictionary file. It is closed in the middle of the loop, so subsequent reads from it will instantly fail. OP could reset the read pointer to the beginning of the file with inputFile.seekg(0);, but why reread the file every time.
Instead read the dictionary file into a std::set with more or less the same code as used in the search:
std::set<std::string> dictionary;
while (getline(inputFile, line))
{
dictionary.insert(line);
}
at the beginning of the program and search the set for the user's input in the loop.
if (dictionary.find(input) != dictionary.end())
{
cout << input << " is spelled correctly.\n";
}
else
{
cout << input << " is not spelled correctly.\n";
}
This should do the trick, you just need to move your getline block in the while loop, and move the file close statement outside the while loop:
#include <iostream>
#include <fstream>
#include <string>
#include <cstdio>
using namespace std;
int main()
{
string line; //holds values from txt file
string input; //holds user-inputted values
ifstream inputFile; //fstream operator declaration
bool isFound = false; //bool value to indicate if the string has been found
inputFile.open("dict.txt", ios::in);
if (inputFile)
{
while (input != "exit")
{
// Rewind file back to beginning every time
inputFile.clear();
inputFile.seekg(0,std::ios::beg);
cout << "Enter word to spellcheck (or exit to end)\n";
getline(cin, input);
while (getline(inputFile, line))
{
if (input == line)
{
isFound = true;
break;
}
else
{
isFound = false;
}
}
if (isFound )
{
cout << input << " is spelled correctly.\n";
}
else
{
if (input != "exit"){ // Don't print message if exiting
cout << input << " is not spelled correctly.\n";
}
}
}
if (input == "exit")
{
cout << "Ending program...\n";
}
inputFile.close();
}
else
{
cout << "Cannot open file\n";
}
return 0;
}

Writing to a file with fstream and cstring

#include <fstream>
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char filename[20] = "filename";
char userInput;
ofstream myFile;
cout << "Enter filename: ";
cin.getline(filename, sizeof(filename));
myFile.open(filename);
if(myFile.fail())
{
cout << "Error opening file: "
<< filename << "\n";
return 1;
}
cout << "Add text to the file: ";
cin.get(userInput);
while(cin.good() && userInput)
{
myFile.put(userInput);
cin.get(userInput);
}
myFile.close();
return 0;
}
Im having trouble terminating the input without force quiting it(It still writes to the file).
This is what I am supposed to do
Receives a line of input from the user, then outputs that
line to the given file. This will continue until the line input
by the user is “-1” which indicates, the end of input.
however I cannot work out the -1 part. Any help would be greatly appreciated everything else seems to work.
You're making things a bit more complicated than they need to be. Why C strings instead of std::string, for example? Using the right (standard-provided) classes generally leads to shorter, simpler and easier-to-understand code. Try something like this for starters:
int main()
{
std::string filename;
std::cout << "Enter filename" << std::endl;
std::cin >> filename;
std::ofstream file{filename};
std::string line;
while (std::cin >> line) {
if (line == "-1") {
break;
}
file << line;
}
}
First of all, the assignment asks to read a line from the user, character-wise input by get() shouldn't be the function to use. Use the member function getline() as you did to recieve the file name and use a comparison function to check against -1:
for (char line[20]; std::cin.getline(line, sizeof line) && std::cin.gcount(); )
{
if (strncmp(line, "-1", std::cin.gcount()) == 0)
break;
myFile.write(line, std::cin.gcount());
}

How to open any input file whether it contains words or numbers and prints it out. C++

So Lets say this is what the input file contains
12
Hello
45
54
100
Cheese
23
How would I print it out on the screen in that order.
This is what I had but it skips some lines.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
int number;
string word;
int loop = 0;
ifstream infile;
infile.open("arraynumbers.txt");
while(infile >> number >> word)
{
if( infile >> number)
{
cout << number << endl;
}
if(infile >> word)
{
cout << word << endl;
}
}
return 0;
}
I suggest using www.cplusplus.com to answer these questions.
However, you are on the right track. Since you are just outputting the contents of the file to stdout, I suggest using readline() and a string. If you need to access the numeric strings as ints, use the atoi() function.
Example:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string line;
ifstream file("arraynumber.txt");
if (file.is_open()) {
while (getline(file, line)) {
cout << line << endl;
}
file.close();
} else cout << "Error opening arraynumber.txt: File not found in current directory\n";
return 0;