A more concise way to load the original line from a C ++ file
Basically I want to load a string from a file that needs to be json encoded.
The way I achieved this is rather verbose for what should be a simple operation:
std::ifstream t(json_path);
std::string stringbuf = std::string(std::istreambuf_iterator<char>(t), std::istreambuf_iterator<char>());
boost::erase_all(stringbuf, "\t");
boost::erase_all(stringbuf, "\n");
boost::erase_all(stringbuf, " ");
Is there a faster way to load a text file into a string and strip out special characters?
+3
source to share
4 answers
You can use std::getline
and erase / remove the idiom with a lambda (or a functor if you don't have C ++ 11 support) like
std::string string_buf(std::istreambuf_iterator<char>(t), {});
string_buf.erase(std::remove_if(string_buf.begin(), string_buf.end(),
[](char c) { return std::isspace(c);}),
string_buf.end()
);
+2
source to share
You can also use std::copy_if
and paste an iterator to copy only the characters you want rather than copying everything by moving bytes around (for example std::remove_if
) and removing the ones you don't need.
#include <algorithm>
#include <fstream>
#include <iostream>
#include <iterator>
#include <string>
int
main(int argc, char **argv)
{
std::string outbuf;
std::ifstream ins(argv[1]);
std::copy_if(std::istreambuf_iterator<char>(ins),
std::istreambuf_iterator<char>(),
std::back_insert_iterator<std::string>(outbuf),
[](char c) { return !std::isspace(c); });
std::cout << outbuf << std::endl;
return 0;
}
+3
source to share
// Open the file
std::ifstream t(json_path);
// Initialize the string directly, no = sign needed.
// C++11: Let second istreambuf_iterator argument be deduced from the first.
std::string stringbuf(std::istreambuf_iterator<char>(t), {});
// C++11: Use a lambda to adapt remove_if.
char ws[] = " \t\n";
auto new_end = std::remove_if( stringbuf.begin(), stringbuf.end(),
[]( char c ) { return std::count( ws, ws + 3, c ); } );
// Boost was doing this part for you, but it easy enough.
stringbuf.erase( new_end, stringbuf.end() );
+1
source to share
You can do it like this:
inFile.open(fileName, ios::in);
if(inFile.fail()) {
cout<<"error opening the file.";
} else {
getline(inFile,paragraph);
cout << paragraph << endl << endl;
}
numWords=paragraph.length();
while (subscript < numWords) {
curChar = paragraph.substr(subscript, 1);
if(curChar==","||curChar=="."||curChar==")"
||curChar=="("||curChar==";"||curChar==":"||curChar=="-"
||curChar=="\""||curChar=="&"||curChar=="?"||
curChar=="%"||curChar=="$"||curChar=="!") {
paragraph.erase(subscript, 1);
numWords-=1;
} else {
subscript+=1;
}
}
cout<<paragraph<<endl;
inFile.close();
-1
source to share