so i have a code that's supposed to find a string of characters in a certain .txt file, if the input is in the file, it says "yey i found it" but when it isnt, its supposed to say "didnt find anything", but it just skips that step and ends.
I'm a beginner so sorry for any obvious mistakes.
#include <stdio.h>
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(void)
{
setlocale(LC_ALL, "");
string hledat;
int offset;
string line;
ifstream Myfile;
cout.flush();
cout << "Welcome, insert the string to find in the file. \n \n \n" << endl;
cin.get();
cout.flush();
Myfile.open("db.txt");
cin >> hledat;
if (Myfile.is_open())
{
while (!Myfile.eof())
{
getline(Myfile, line);
if ((offset = line.find(hledat, 0)) != string::npos)
{
cout.flush();
cout << "Found it ! your input was : " << hledat << endl;
}
}
Myfile.close();
}
else
{
cout.flush();
cout << "Sorry, couldnt find anything. Your input was " << hledat << endl;
}
getchar();
system("PAUSE");
return 0;
}
There are three possible cases.
The file was not successfully opened.
The file was successfully opened, but the string was not found.
The file was successfully opened, and the string was found.
You have a printout for cases 1 and 3, but not 2.
By the way, your loop condition is wrong. Use the result of the call to getline, which is the ostream object itself after the read attempt.
while (getline(MyFile, line))
{
...
}
The loop will terminate upon an unsuccessful read attempt, which will happen after you read the last line. The way you have it, you will try to read after the last line, which will be unsuccessful, but you will still try to process that non-existent line because you don't check eof until the loop starts over.
Just comment out //cin.get(); , you dont need it.
Output:
Welcome, insert the string to find in the file.
apple
Found it ! your input was : apple
Other than that, it works like a charm.
Corrected code:
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(void)
{
setlocale(LC_ALL, "");
string hledat;
int offset;
string line;
ifstream Myfile;
cout.flush();
cout << "Welcome, insert the string to find in the file. \n \n \n" << endl;
//cin.get(); <----- corrected code
cout.flush();
Myfile.open("db.txt");
cin >> hledat;
if (Myfile.is_open())
{
while (!Myfile.eof())
{
getline(Myfile, line);
if ((offset = line.find(hledat, 0)) != string::npos)
{
cout.flush();
cout << "Found it ! your input was : " << hledat << endl;
}
}
Myfile.close();
}
else
{
cout.flush();
cout << "Sorry, couldnt find anything. Your input was " << hledat << endl;
}
getchar();
system("PAUSE");
return 0;
}
Related
so I don't know how to explain this correctly but gonna try my best.
I'm trying to save a file into a string, it's not a .txt file, it's a .umsbt file so it has weird ASCII characters (like 00, 0A, 0E, 1A...) so when I save the .umsbt into the string using getline(); and then print it using cout, the whole file isn't printed, and when I open the actual file through HxD (hex editor) I see that the print stopped before a 1A character, did some tests and it's the 1A character's fault.
This is my code
#include <iostream>
#include <stdlib.h>
#include <fstream>
#include <string>
#include <string.h>
#include <conio.h>
#include <sstream>
using namespace std;
string line; //the file is stored here
string name; //name of the file
void printfile() {
int o = 0;
int fileCount;
ifstream file;
file.open(name, ios::in);
if (file.fail()) {
cout << "Not found \n";
cin.get();
cin.get();
exit(1);
}else {
file.seekg(0, ios::end);
fileCount = file.tellg();
file.seekg(0);
while (!file.eof()) {
getline(file, line);
cout << "file character count: " << fileCount << endl;
cout << "string character count: " << line.length() << "\n" << endl;
for (int i = 0; i < line.length(); i++) {
cout << line[i];
o++;
if (o == 16) {
cout << "\n";
o = 0;
}
}
}
file.close();
}
}
int main()
{
cin.ignore(26, '\n');
cout << "Write the name of your file (.umsbt included) \n" << endl;
cin >> name;
cout << "\n";
printfile();
cin.get();
cin.get();
return 0;
}
Hope someone can help me, I'm currently trying to remove/replace all of the 1A characters in any file, and the restriction is that you have to do it in the ifstream itself, cause you can't save it in a string (will cause the problem with 1A and the file won't be fully saved)
(Here's a pic of the file opened up in HxD hope you get an idea of it https://imgur.com/a/1uQzOPq)
Thank you in advance
Seems that you are using binary files and not a normal text file.
Check out these links to learn about binary files.
https://study.com/academy/lesson/writing-reading-binary-files-in-c-programming.html
https://computer.howstuffworks.com/c39.htm
Bye,
Samuel
I am trying to create a program that will load the CSV file and based upon the inputted word search through the file and return any lines that contain the word. The CSV file is a mass download of tweets and has the following columns:
Date & Time Created
The Tweet
The tweets are also surrounded by b'TWEET TEXT HERE' so would need to remove the b' ' from when it printed out. I am unable to change anything to do with the CSV file sadly so cant manually remove it. The issues I am having are:
Listing the total amount of tweets within the file the program just freezes
Removing the b' ' from the tweets
The else statement causes "not found" to be constantly printed
Code I currently have that is returning the tweets that contain the inputted word but also the false positive.
The current output when running the below code
#include "stdafx.h"
#include <cstring>
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main()
{
string token;
ifstream fin;
fin.open("sampleTweets.csv");
if (fin.is_open())
{
cout << "File opened successfully" << "\n";
}
else {
cout << "Error opening file" << "\n";
}
cout << "Enter search word: ";
cin >> token;
"\n";
string line;
while (getline(fin, line)) {
if (line.find(token) != string::npos) {
cout << line << endl;
} else {
cout << token << " not found" << endl;
}
}
fin.close();
char anykey;
cout << "press any key";
cin >> anykey;
return 0;
}
Code I was using for counting total tweets
int count = 0;
char str[140];
while (!fin.eof())
{
fin.getline(str, 140);
count++;
}
cout << "Number of lines in file are " << count;
Any help on this would be amazing as I am quite new to C++ and not sure where to go from here!
You can remove the "b" with erase:
if (line.find(token) != string::npos){
int n= line.find(",");
line.erase(n+1, 3);
cout << line << endl;
}
and you can count the lines inside the while loop:
int count = 0;
while (getline(fin, line)) {
++count;
...
}
EDIT: you can remove the extra quotes and commas like so:
line[n] = ' '; // change comma int space
line.erase(n+1, 4); // remove "b""
line.resize(line.size()-5); // remove trailing """,,
I am trying to create a very simple program that writes to a file, but can't understand why it won't let me write to a file if I put it within an if statement! Here's the code:
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include <stdlib.h>
using namespace std;
void readFile();
int main()
{
string line;
string today;
string readOrWrite;
cout << "Do you want to write to a file or read a file? " << endl;
cout << "Type \"write\" or \"read\" ";
cin >> readOrWrite;
if (readOrWrite == "read")
{
readFile();
}
else if (readOrWrite == "write")
{
cout << "How are you today? " << endl;
getline(cin, today);
ofstream myJournal;
myJournal.open("Journal.txt", ios::app);
myJournal << today << " ";
myJournal.close();
}
else
{
return 0;
}
return 0;
}
void readFile()
{
ifstream myJournal;
myJournal.open("Journal.txt");
string line;
if (myJournal.is_open())
{
while (getline(myJournal, line))
{
cout << line << endl;
}
myJournal.close();
}
else
{
cerr << "Error opening file ";
exit(1);
}
}
When I move it out of the if statement, it works smoothly and is able to write to the file, but when I place it inside, it opens the program, asks me the "Do you want to write to a file or read a file? ", I type "write", then it says "How are you today? " and then ends the program, printing "Press any key to continue...". Any help?
it says "How are you today? " and then ends the program, printing "Press any key to continue...". Any help?
std::istream::ignore should help in that case you are encountering.
cout << "How are you today? " << endl;
cin.ignore(10, '\n'); // Inserted
getline(cin, today);
Why do we need that in between?
It takes out 10 characters, which is enough amount of length, from the buffer and stops if it encounters a newline, which is '\n'. (Remember that you press the key 'enter' after typing "wrtie")
By doing so you can move on to the next new line, preventing std::cin from any parse failure.
More info : http://www.cplusplus.com/reference/istream/istream/ignore/
I've read the lines from a textfile and i want to check if that line contains the $ sign.
That's what i got so far:
int main() {
ifstream data_store;
string line;
data_store.open("c:\\test.txt");
while (!data_store.eof())
{
getline(data_store, line);
if (line.find("$"))
cout << "1: " << line << endl;
}
data_store.close();
system("PAUSE");
return 0;
}
Furthermore how can i output them to a file ?
To check if a line contains something using std::string::find to need to check the returned value from find to make sure it is a valid return. To do that we compare it against std::string::npos as that is what find() will return if it does not find anything. This is the reason it finds every line as std::string::npos is still considered true when evaluated as a bool. So refactoring your code you would have:
while (getline(data_store, line))
{
if (line.find("$") != std::string::npos)
cout << "1: " << line << endl;
}
I also changed the while loop as using eof is not how to control a while loop. for more information on that see Why is “while ( !feof (file) )” always wrong?
As far as outputting the string to a file see: How to write std::string to file?
It's a minor thing, but a variant of #NathanOliver's solution, is to use a for loop:
ifstream data_store("c:\\test.txt");
for ( string line; getline(data_store, line); ) {
if ( line.find("$") != string::npos )
cout << "1: " << line << endl;
}
// ...
The benefit here is that line is now local only to the loop, which is what it should be since that is the only place it is used.
I did it yesterday forgot to update.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
bool contains_number(const string &c);
int main()
{
int count = 0;
{
string line1[100];
ifstream myfile("D:/Users/Jarvan/Desktop/test.txt");
int a = 0;
if (!myfile)
{
cout << "Error opening output file" << endl;
system("pause");
return -1;
}
while (!myfile.eof())
{
getline(myfile, line1[a], '\n');
if (contains_number(line1[a]))
{
count += 1;
cout << line1[a] << "\n";
}
else cout << "\n";
}
}
cout << count <<endl;
system("pause");
return 0;
}
bool contains_number(const string &c)
{
return (c.find_first_of("$") != string::npos);
}
#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());
}