![](/img/trans.png)
[英]Is there a way to read content of C++ raw string literal from non C/C++ file?
[英]More concise way to load a raw string from a file c++
基本上我想要做的是從一個要編碼為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, " ");
有沒有更簡單的方法將文本文件加載到字符串並刪除特殊字符?
您還可以使用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;
}
您可以使用std::getline
和erase / remove idiom與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()
);
// 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() );
你可以這樣做:
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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.