read word to file c++ - c++

I want get from user word and put into place in file where is certian word.
I have problem with getline.
In new file I don't have any new line.
When I add Newline to string which I write to file, this line is read two times and writeto file to times (I think that bcoz I saw this newfile)
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string contain_of_file,bufor,word,empty=" ",new_line="\n";
string conection;
string::size_type position;
cout<<"Give a word";
cin>>word;
ifstream NewFile;
ofstream Nowy1;
Nowy1.open("tekstpa.txt", ios::app);
NewFile.open("plik1.txt");
while(NewFile.good())
{
getline(NewFile, contain_of_file);
cout<<contain_of_file;
position=contain_of_file.find("Zuzia");
if(position!=string::npos)
{
conection=contain_of_file+empty+word+new_line;
Nowy1<<conection;
}
Nowy1<<contain_of_file;
}
Nowy1.close();
NewFile.close();
cin.get();
return 0;
}

The problem here is not your reading. directly, but about your loop.
Do not loop while (stream.good()) or while (!stream.eof()). This is because the eofbit flag is not set until after you try to read from beyond the file. This means that the loop will iterate one extra time, and you try to read from the file but the std::getline call will fails but you don't notice it and just continue as if nothing happened.
Instead do
while (std::getline(NewFile, contain_of_file)) { ... }
And an unrelated tip: The variable conection is not needed, you can instead do just
Nowy1 << contain_of_file << ' ' << word << '\n';

Related

I'm not able to read and write to the same file

I'm trying to have the code read and repeat the last line of text in an input file, and put an underscore line right below it. As the code is, it will cout the last line to the terminal but won't output anything to the file. If I remove the while(getline()), the underscore line will appear but then it can't find the line string.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
string underscoreDiv (int lengthText){
string underscores;
for(int i{}; i<lengthText; i++)
{
underscores += "_";
}
return underscores + "\n";
}
int main(){
fstream fileApp("C:\\Users\\trist\\OneDrive\\Documents\\Notes_application\\Notes_app.txt", ios::in | ios::app);
if(fileApp.is_open()){
string underscore;
string line;
underscore=underscoreDiv(80);
while(getline(fileApp, line)){} ///removing this line
cout<<line;
fileApp<<"\n"<<line<<endl;
fileApp<<underscore<<endl;
fileApp.close();
}
else{
cout<<"Text file not file";
}
system("C:\\Users\\trist\\OneDrive\\Documents\\Notes_application\\Notes_app.txt");
return 0;
}
I wrote this modified code that reads the last line and prints it and then prints the underscore line but I'm having to open, close, then reopen the input file which makes it too slow.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
string underscoreDiv (int lengthText){
string underscores;
for(int i{}; i<lengthText; i++)
{
underscores += "_";
}
return underscores + "\n";
}
int main(){
fstream fileApp("C:\\Users\\trist\\OneDrive\\Documents\\Notes_application\\Notes_app.txt", ios::app | ios::in);
string underscore;
string line;
if(fileApp.is_open()){
underscore=underscoreDiv(80);
while(getline(fileApp, line)){}
cout<<line;
fileApp<<"\n"<<line<<endl; ///these 2 lines don't do anything
fileApp<<underscore<<endl;
fileApp.close();
}
else{
cout<<"Text file not file";
}
fileApp.open("C:\\Users\\trist\\OneDrive\\Documents\\Notes_application\\Notes_app.txt", ios::app | ios::in);
fileApp<<"\n"<<line<<endl;
fileApp<<underscore<<endl;
///system("C:\\Users\\trist\\OneDrive\\Documents\\Notes_application\\Notes_app.txt"); ///too lazy to write a close statement here.
return 0;
}
The problem that you encounter has to do with the state of the stream. After each IO operation the result of that operation is stored in internhal state bits of the stream.
There is a very good overview in the CPP reference here. Please especially look at the table at the bottom of this page.
After the execution of the loop while(getline(fileApp, line)){} the eof bit of the stream is set. And only because of that, the while loop stops. Look in the table. If the eof bit is set, the bool function will return false. And since the while-loop excpects a boolean value, the bool function of the stream (that will be returned by std::getline) will be called.
So, now that we reached the end of the file, the stream is in fail state.
And then, no further IO operation on this stream will be executed.
Solution: Call the streams clear function after your while loop: fileApp.clear();
Recommendation: In general you should always check the state of a stream after IO operations.

Finding certain characters in a line of string

I want to be able to a string that contains certain characters in a file that contains one string per line.
#include <iostream>
#include <fstream>
#include <string>
int main(){
string line;
ifstream infile;
infile.open("words.txt");
while(getline(infile, line,' ')){
if(line.find('z')){
cout << line;
}
}
}
That's my attempt at finding all the string that contains the character z.
The text file contains random strings such as
fhwaofhz
cbnooeht
rhowhrj
perwqreh
dsladsap
zpuaszu
so with my implementation, it should only print out the strings with the character z in it. However, it seems to be reprinting out all the contents from the text file again.
Problem:
In your file the strings aren't separated by a space (' ') which is the end delimiter, they are separated by a end of line ('\n'), that is a different character. As a consequence, in the first getline everything goes to line. line contains all the text in the file, including z's, so all the content is printed. Finally, the code exits the while block after running once because getline reaches the end of the file and fails.
If you run this code
#include <iostream>
#include <fstream>
#include <string>
int main(){
std::string line;
std::ifstream infile;
infile.open("words.txt");
while(getline(infile, line,' ')){
std::cout << "Hi";
if(line.find('z')){
std::cout << line;
}
}
}
"Hi" will be only printed once. That is because the while block is only executed once.
Additionaly, see that line.find('z') won't return 0 if not match is found, it will return npos. See it running this code (As it says here):
#include <iostream>
#include <fstream>
#include <string>
int main(){
std::string line;
std::ifstream infile;
infile.open("words.txt");
while(getline(infile,line)){
std::cout << line.find('z');
if(line.find('z')){
std::cout << line << "\n";
}
}
}
Solution:
Use getline(infile,line) that is more suitable for this case and replace if(line.find('z')) with if(line.find('z') != line.npos).
while(getline(infile,line)){
if(line.find('z') != line.npos){
std::cout << line << "\n";
}
}
If you need to put more than one string per line you can use the operator >> of ifstream.
Additional information:
Note that the code you posted won't compile because string, cout and ifstream are in the namespace std. Probably it was a part of a longer file where you were using using namespace std;. If that is the case, consider that it is a bad practice (More info here).
Full code:
#include <iostream>
#include <fstream>
#include <string>
int main(){
std::string line;
std::ifstream infile;
infile.open("words.txt");
while(getline(infile,line)){
if(line.find('z') != line.npos){
std::cout << line << "\n";
}
}
}
getline extracts characters from the source and stores them into the variable line until the delimitation character is found. Your delimiter character is a space (" "), which isn't present in the file, so line will contain the whole file.
Try getline(infile, line, '\n') or simply getline(infile, line) instead.
The method find returns the index of the found character, where 0 is a perfectly valid index. If the character is not found, it returns npos. This is a special value whcih indicates "not found", and it's nonzero to allow 0 to refer to a valid index. So the correct check is:
if (line.find('z') != string::npos)
{
// found
}

Read line in C++ till EOF

I'm writing a function that reads line by line from cin and returns when it sees ; character.
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <string.h>
using namespace std;
int read_cmd(char *cmd)
{
cout << "Please enter a string: \n";
cmd[0]='\0';
while(1){
char currentLine[10000];
currentLine[0]='\0';
cin.getline(currentLine,10000);
if (strcmp(currentLine,";")==0){
break;
}
strcat(cmd, "\n");
strcat(cmd, currentLine);
}
return 0;
}
int main(){
char cmd[1000];
while (1){
read_cmd(cmd);
cout<< cmd << endl;
}
}
I then tested it using text fed from another file via pipe.
./read_cmd < test_file
contents of test_file:
line 1
line 2
;
This outputs results just fine, however it gives me a segmentation fault at the end. Is there a way for cin to check if it's coming across an EOF and terminates?
To detect the EOF you should use something like:
while (cin.good() && !cin.eof())
{
// Read the file
}
See the documentation for cin, in particular the good() (for error checking) and eof() member functions.
In particular this example might be helpful.
I would highly suggest the use of the string object for something like this, that way you're not wasting space, as well as ensuring that you have enouch space. You can also do it without a loop.
string currentLine;
getline(cin, currentLine, ';');
Now, if you need to get just the last line with has the semi-colon, a loop is necessary, but still you can do it at little more easily.
string currentLine;
while(getline(cin, currentLine)){
if(currentLine.find(";") != string::npos){
break;
}
}
Use strings to pass things around as well. There's always the .clear() method as well that any string has for easy emptying.
string getline
string Object

Read File line by line to variable and loop

I have a phone.txt like:
09236235965
09236238566
09238434444
09202645965
09236284567
09236235965
..and so on..
How can I process this data line by line in C++ and add it to a variable.
string phonenum;
I know I have to open the file, but after doing so, what is done to access the next line of the file?
ofstream myfile;
myfile.open ("phone.txt");
and also about the variable, the process will be looped, it will make the phonenum variable the current line its processing from the phone.txt.
Like if the first line is read phonenum is the first line, process everything and loop; now the phonenum is the 2nd line, process everything and loop until the end of the last line of the file.
Please help. I'm really new to C++. Thanks.
Read the comments inline please. They will explain what is going on to assist you in learning how this works (hopefully):
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
int main(int argc, char *argv[])
{
// open the file if present, in read mode.
std::ifstream fs("phone.txt");
if (fs.is_open())
{
// variable used to extract strings one by one.
std::string phonenum;
// extract a string from the input, skipping whitespace
// including newlines, tabs, form-feeds, etc. when this
// no longer works (eof or bad file, take your pick) the
// expression will return false
while (fs >> phonenum)
{
// use your phonenum string here.
std::cout << phonenum << '\n';
}
// close the file.
fs.close();
}
return EXIT_SUCCESS;
}
Simple. First, note that you want an ifstream, not an ofstream. When you're reading from a file, you're using it as input - hence the i in ifstream. You then want to loop, using std::getline to fetch a line from the file and process it:
std::ifstream file("phone.txt");
std::string phonenum;
while (std::getline(file, phonenum)) {
// Process phonenum here
std::cout << phonenum << std::endl; // Print the phone number out, for example
}
The reason why std::getline is the while loop condition is because it checks the status of the stream. If std::getline fails in anyway (at the end of your file, for example), the loop will end.
You can do that :
#include <fstream>
using namespace std;
ifstream input("phone.txt");
for( string line; getline( input, line ); )
{
//code
}

C++ dealing with files

I have a problem working in C++ with txt files.. First of all, I want to make a program which
have .cpp and .h files.. which have classes and functions.
So here is my problem:
for example, i have txt file which contains 5 lines of text (players names). So I want to make every line of that txt to be a variable of string.. But as long as I want to use that new variables they suddently disappears.
Here is program code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
string line;
int i;
string player[5];
ifstream myfile ("1-Efes Pilsen.txt");
if (myfile.is_open())
{
while ( myfile.good() )
{
for (i=0;i<5;i++)
{
getline (myfile,line);
player[i] = line;
}
// after this point I still can use new variables
}
}
else cout << "Unable to open file";
cout << player[1]; // <--- NOT WORKING. WHY?
myfile.close();
}
While it is not clear to me how it's not working, I can guess that there are more contents in the file than just 5 strings (perhaps another newline) which causes the while condition to evaluate to true causing the for loop to read 5 lines (which will fail and not actually read anything) and replace the good values in the string array with crappy ones (empty string).
Instead of having an outer while loop, you probably want to add the condition to the for loop itself; something along the lines of:
for (i=0;i<5 && myfile.good();i++)
{
getline (myfile,line);
player[i] = line;
}