从文件c ++加载原始字符串的更简洁方法

时间:2015-05-16 15:11:06

标签: c++ json file

基本上我想要做的是从一个要编码为json的文件中加载一个字符串。

我实现这一点的方式对于简单操作应该是非常冗长的:

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, " ");

是否有更简洁的方法将文本文件加载到字符串并删除特殊字符?

4 个答案:

答案 0 :(得分:3)

你也可以使用std::copy_if和插入迭代器来复制你想要的字符而不是复制所有字符,改变字节周围的字节(例如,std::remove_if),并删除那些你不喜欢的字符不想要。

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

答案 1 :(得分:2)

您可以使用std::getline并使用lambda(或仿函数,如果您没有C ++ 11支持)删除/删除习惯用法,例如

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 :(得分:1)

// 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's easy enough.
stringbuf.erase( new_end, stringbuf.end() );

答案 3 :(得分:-1)

你可以这样做:

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();