How to add spaces into a text file? - c++

I have a text file like this:
100,Nguyen Van A,2004
101,Tran Thi B,2004
102,Vo Van C,2005
103,Truong Thi D,2005
How can I add one blank space right after each "," into that file using C++?
I've tried using find() function but nothing worked.
svFile.open("list_student.txt");
while (getline(svFile, line, ','))
{
if (line.find(",", 0) != string::npos)
svFile << " ";
}

Two options, read and write the file character by character, or option 2, read the entire text file into a string and then perform your required changes and write the file back:
Option 1 (Character by Character):
char ch;
fstream fin("list_student.txt", fstream::in);
fstream fout("list_student_result.txt", fstream::out);
while (fin >> noskipws >> ch) {
fout << ch;
if (ch==',')
{
fout << ' ';
}
}
fout.close();
Option 2 (Read/Write entire file):
#include <iostream>
#include <fstream>
int main()
{
// Read the entire file
std::ifstream t("list_student.txt");
std::stringstream buffer;
buffer << t.rdbuf();
std::string myString = buffer.str();
size_t start = 0;
int pos = 0;
// Set your start character and replace with string here
std::string comma(",");
std::string replaceWith(", ");
// Replace the comma "," with ", " (and a space)
while ((pos = myString.find(comma, pos)) != std::string::npos) {
myString.replace(pos, comma.length(), replaceWith);
pos += replaceWith.length();
}
// Write the formatted text back to a file
std::ofstream out("list_student_result.txt");
out << myString;
out.close();
return 0;
}

Related

Trying to read and write into files using c++, but not able to replace the substring correctly

So, what I am trying to do is, read from a file and write into another.
std::ifstream fs;
fs.open ("/Users/aditimalladi/CLionProjects/file/log.txt");
string str_file;
std::ofstream fs2;
fs2.open ("/Users/aditimalladi/CLionProjects/file/log-copy.txt ");
if(!fs || !fs2)
{
std::cout<<"ERROR";
exit(0);
}
string str;
while(getline(fs,str))
{
while(true) {
std::cout<<"\n This is the string \n"<<str<<std::endl;
size_t index = str.find("≠", index);
if (index == std::string::npos) break;
str.replace(index, 1, "-");
index += 1;
std::cout<<"\n This is the new replaced string \n"<<str<<std::endl;
}
fs2 << str << std::endl;
}
fs.close();
fs2.close();
What my end goal is to be able to read a line and replace that line in the same file after making some changes.But first I want this basic program to work before I move forward.
A problem in the snippet you posted is that you are trying to replace a string "≠", which contains non-ASCII character that can be encoded with multiple bytes. So those lines:
size_t index = str.find("≠", index);
if (index == std::string::npos)
break;
str.replace(index, 1, "-");
// note this ^^^
Will replace only the first byte of the encoding, leaving the others.
You could use the correct size of the string to be replaced or rewrite your program using the regular expression library:
#include <iostream>
#include <string>
#include <fstream>
#include <regex>
int main()
{
std::ifstream fs {"/Users/aditimalladi/CLionProjects/file/log.txt"};
std::ofstream fs2 {"/Users/aditimalladi/CLionProjects/file/log-copy.txt"};
if(!fs || !fs2)
{
std::cerr << "Error, can't open files";
exit(1);
}
std::regex a {"≠"};
std::string line;
while ( std::getline(fs, line) )
{
fs2 << std::regex_replace(line, a, "is not equal to") << '\n';
}
}

how to remove these empty lines

i can detect the empty line in text but not getting how to delete it
please can you give me some tips how to delete that detected lines
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;
int main()
{
// open input file
std::ifstream ifs( "in_f1.txt" );
std::fstream ofs( "out_f1.txt" );
char c;
char previous_c;
// squeeze whitespace
std::string word;
ifs >> word;
ofs << word;
while (ifs)
{
if (c==' ')
{
ofs.put(c);
while (c==' '&&ifs)
{
ifs.get (c);
;}
}
if (c=='\v')
{
previous_c=c;
while (c=='\v'&&ifs)
{
ifs.get (c);
;}
ofs.put(previous_c);
};
// read line
std::string line;
std::getline( ofs, line );
// append flag and remove 'empty lines'
int flag = 2;
while( getline( ofs, line ) )
{
if( line == " " )
{
flag = 2;
continue;
}
cout << line << " " << flag << endl;
flag = 0;
}
ifs.close();
ofs.close();
}}
you are looking in the output stream for an empty line, after you copy the characters to it.. A stream is not intended to be something we edit like a string, so stop thinking on it that way..
instead you need to add the logic before you put the characters into the stream.
the easiest approach is to have a temporary stream, that you copy from input to.
then for each line, copy the temporary stream to output stream, if and only if, it contains characters different from whitespace.
void remove_empty_lines(std::istream& in, std::ostream& out)
{
std::string line;
while (std::getline(in, line))
if (!line.empty())
out << line << '\n';
}
N.B. This will add a newline to the end of the file even if there isn't one in the original.

How can I find and replace a line of data in a text file c++

I am trying to find and replace a line of data in a text file in c++. But I honestly have no idea where to start.
I was thinking of using
replaceNumber.open("test.txt", ios::in | ios::out | ios_base::beg | ios::app);
To open the file at the beginning and append over it but this doesn't work.
Does anyone know of a way to achieve this task?
Thanks
Edit: My text file is only one line and it contains a number for example 504. The user then specifies a number to subtract then the result of that should replace the original number in the text file.
Yes, you can do this using std::fstream, here's a quick implementation i whipped up real quick. You open the file, iterate over each line in the file, and replace any occurrences of your substring. After replacing the substring, store the line into a vector of strings, close the file, reopen it with std::ios::trunc, and write each line back to the empty file.
std::fstream file("test.txt", std::ios::in);
if(file.is_open()) {
std::string replace = "bar";
std::string replace_with = "foo";
std::string line;
std::vector<std::string> lines;
while(std::getline(file, line)) {
std::cout << line << std::endl;
std::string::size_type pos = 0;
while ((pos = line.find(replace, pos)) != std::string::npos){
line.replace(pos, line.size(), replace_with);
pos += replace_with.size();
}
lines.push_back(line);
}
file.close();
file.open("test.txt", std::ios::out | std::ios::trunc);
for(const auto& i : lines) {
file << i << std::endl;
}
}
You can use std::stringstream to convert the string read from the file to an integer and use std::ofstream with std::ofstream::trunc to overwrite the file.
#include <iostream>
#include <string>
#include <fstream>
#include <list>
#include <iomanip>
#include <sstream>
int main()
{
std::ifstream ifs("test.txt");
std::string line;
int num, other_num;
if(std::getline(ifs,line))
{
std::stringstream ss;
ss << line;
ss >> num;
}
else
{
std::cerr << "Error reading line from file" << std::endl;
return 1;
}
std::cout << "Enter a number to subtract from " << num << std::endl;
std::cin >> other_num;
int diff = num-other_num;
ifs.close();
//std::ofstream::trunc tells the OS to overwrite the file
std::ofstream ofs("test.txt",std::ofstream::trunc);
ofs << diff << std::endl;
ofs.close();
return 0;
}

how to disregard specific new lines in reading from a text file by c++

Wherever, there is a new line or ("\n") and a space (" ") immediately after the the new line, I want to disregard the "\n" and just print the space in my output, how could I do this?
This is an example:
newegg
bizrate
want to change it to :
newegg bizrate
I am confused since I guess I cannot do it by reading line by line! below is my rough code, which I don't know how to continue ...
Thanks a lot in advance.
ifstream file ("input.txt");
ofstream output("output.txt");
string line;
if(file.is_open())
{
while (!file.eof())
{
getline (file, line);
if (line.find("\n"+' ') != string::npos)
{
??
}
Do it like this. The function getline() will read till \n character
getline(file, line);
cout<<line;
while (!file.eof())
{
getline(file, line);
if (line[0]==' ')
{
cout <<" "<<line;
}
else
{
cout <<"\n"<<line;
}
}
The function getline() (documentation here) will read and throw away the \n character, so there's no need to search for it in the string.
Just do something like this:
bool first = true;
while (!file.eof())
{
getline(file, line);
// you may want to check that you haven't read the EOF here
if (!first)
{
cout << " ";
}
else
{
first = false;
}
cout << line;
}
You might want this:
#include <cctype>
#include <iostream>
#include <sstream>
int main() {
std::istringstream input(""
"newegg\n"
" bizrate\n"
"End");
std::string line;
while(std::getline(input, line)) {
while(std::isspace(input.peek())) {
std::string next_line;
std::getline(input, next_line);
line += next_line;
}
std::cout << line << '\n';
}
}
Please note: A test for EOF is likely wrong.

C++: File I/O having difficulty with opening and working with it

I'm having difficulty opening files and processing what is inside of them. What i want to do is
pull a line from the input file
init an istreamstream with the line
pull each word from the istringstream
i. process the word
do my specific function i've created
ii. write it to the output file
I'm not sure how to go about doing 1-3 can anyone help with my functions? This is what i have so far...
string process_word(ifstream &inFile){
string line, empty_str = "";
while (getline(inFile,line)){
empty_str += line;
}
return empty_str;
}
int main(){
string scrambled_msg = "", input, output, line, word, line1, cnt;
cout << "input file: ";
cin >> input;
cout << "output file: ";
cin >> output;
ifstream inFile(input);
ofstream outFile(output);
cout << process_word(inFile);
}
std::vector<std::string> process_word(std::ifstream& in)
{
std::string line;
std::vector<std::string> words;
while (std::getline(in, line)) // 1
{
std::istringstream iss{line}; // 2
std::move(std::istream_iterator<std::string>{in},
std::istream_iterator<std::string>{},
std::back_inserter(words));
}
return words;
}
int main()
{
std::ifstream in(file);
std::ofstream out(file);
auto words = process_word(in);
for (auto word : words)
// 3 i.
std::move(words.begin(), words.end(), // 3 ii.
std::ostream_iterator<std::string>{out});
}