Getline(); extraction stops with the 1A character - c++

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

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;
}
}

I/O program stuck in loop C++

I'm working on a code that reads in a C++ source file and converts all ‘<’ symbols to “<” and all ‘>’ symbols to “>”. I wrote out the main method and everything compiled nicely but now that I'm actually writing out my convert function at the top of the program, I'm stuck in an infinite loop and I'm hitting a wall on what the culprit is. Could someone help me out?
I included the whole program in case the problem lies in my I/O coding but I surrounded the function with slashes. Hopefully I won't get flamed.
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
#include <cstring>
using namespace std;
//FUNCTION GOES THROUGH EACH CHARACTER OF FILE
//AND CONVERTS ALL < & > TO < or > RESPECTIVELY
//////////////THIS IS THE FUNCTION IN QUESTION//////////
void convert (ifstream& inStream, ofstream& outStream){
cout << "start" << endl;
char x;
inStream.get(x);
while (!inStream.eof()){
if (x == '<')
outStream << "<";
else if (x == '>')
outStream << ">";
else
outStream << x;
}
cout << "end" << endl;
};
///////////////////////////////////////////////////////////////////////////
int main(){
//FILE OBJECTS
ifstream inputStream;
ofstream outputStream;
string fileName;
//string outFile;
//USER PROMPT FOR NAME OF FILE
cout << "Please enter the name of the file to be converted: " << endl;
cin >> fileName;
//outFile = fileName + ".html";
//ASSOCIATES FILE OBJECTS WITH FILES
inputStream.open(fileName.c_str());
outputStream.open(fileName + ".html");
//CREATES A CONVERTED OUTPUT WITH <PRE> AT START AND </PRE> AT END
outputStream << " <PRE>" << endl;
convert(inputStream, outputStream);
outputStream << " </PRE>" << endl;
inputStream.close();
outputStream.close();
cout << "Conversion complete." << endl;
return 0;
}
It isn't a good approach to manipulate a file while you're reading it. The right way is, first read the whole file, store the data, manipulate the stored data, and then update the file. Hope this code will help you :)
void convert()
{
int countLines = 0; // To count total lines in file
string *lines; // To store all lines
string temp;
ifstream in;
ofstream out;
// Opening file to count Lines
in.open("filename.txt");
while (!in.eof())
{
getline(in, temp);
countLines++;
}
in.close();
// Allocating Memory
lines = new string[countLines];
// Open it again to stroe data
in.open("filename.txt");
int i = 0;
while (!in.eof())
{
getline(in, lines[i]);
// To check if there is '<' symbol in the following line
for (int j = 0; lines[i][j] != '\0'; j++)
{
// Checking the conditon
if (lines[i][j] == '<')
lines[i][j] = '>';
}
i++;
}
in.close();
// Now mainuplating the file
out.open("filename.txt");
for (int i = 0; i < countLines; i++)
{
out << lines[i];
if (i < countLines - 1)
out << endl;
}
out.close();
}

C++ How do i add a string to an existing text file without overwriting it?

I have coded a programm which can load one text file, can decide how long each word is and can write txt files based on the length of the words. But when i run the programm, the new text files are always filled with just one word(each new word with an already existing text file for his length just overrides the text file)
The start text file looks like this():
http://i.stack.imgur.com/WBaRf.png
My new created text files(named after their length for example: 7.txt) after i runned the programm:
http://i.stack.imgur.com/6QKgE.png
My code:
#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;
int main(int argc, char *argv[])
{
char filename[128];
ifstream file;
char line[100];
cout << "Input filename: " << flush;
cin.getline(filename, 127);
file.open(filename, ios::in);
if (file.good())
{
file.seekg(0L, ios::beg);
int number = 0;
while (!file.eof())
{
file.getline(line, 100);
stringstream stream;
stream << line;
number++;
cout <<"Number: "<< number << " length: " << stream.str().length() << " " << line << endl;
std::stringstream sstm;
int laenge = stream.str().length();
string txt = ".txt";
sstm << laenge << txt;
string result = sstm.str();
std::ofstream outFile(result);
outFile << line << endl;
outFile.close();
}
}
else
{
cout << "File not found" << endl;
}
while (true)
{
};
return 0;
}
My goal is that i have sorted the whole words into the file their files, the only problem is that they overwrite themself... How can i get rid off that?
If you don't want to overwrite the content of the file, you can open the file and specify that you want to append to the file:
std::ofstream outFile(result, ios::app);
// ^^^^^^^^

Numbering Lines in a File With C++

I wrote a quick C++ program that asks the user for a input text file and an output text file. The program is then supposed to number the lines in the file on the left margin. However, I cannot seem to get it working properly, it compiles fine but does not number the lines like it is supposed to. I believe it is a logical error on my part. I am also not too familiar with file i/o in C++ as I am just learning it now using old school textbooks.
Here is the file:
#include <iostream>
#include <fstream>
#include <string>
#include <cassert>
#include <cstdio>
using namespace std;
int main(void)
{int i = 0 , num = 1;
string inputFileName;
string outputFileName;
string s;
ifstream fileIn;
ofstream fileOut;
char ch;
cout<<"Enter name of input file: ";
cin>>inputFileName;
cout<<"Enter name of output file: ";
cin>>outputFileName;
fileIn.open(inputFileName.data());
fileOut.open(outputFileName.data());
assert(fileIn.is_open() );
assert(fileOut.is_open() );
while (!(fileIn.eof()))
{ch=fileIn.get();
if (ch=='\n') num++;
fileOut << num << "\n";
s.insert(i,1,ch); //insert character at position i
i++;
}
fileOut << s;
fileIn.close();
fileOut.close();
return 0;
}
If anyone could point me in thr right direction or give me some tips I would be eternally grateful.
int i = 0;
string line;
while (getline(infile, line))
{
outfile << (i++) << " " << line << "\n";
}

Cout doesn't print on display (console)

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;
}