草庐IT

c++ - 从文件中删除注释并保留整数

coder 2024-02-18 原文

我正在尝试从我的 .txt 文件中删除评论。我的文本文件如下所示:

(* Sunspot data collected by Robin McQuinn from *)
(* http://sidc.oma.be/html/sunspot.html         *)

(* Month: 1749 01 *) 58
(* Month: 1749 02 *) 63
(* Month: 1749 03 *) 70
(* Month: 1749 04 *) 56

注释是 (* 和 *) 之间的所有内容。我只需要保留此文件中的 58、63、70 和 56。

我的代码删除了一些字符,但没有正确删除。我的代码如下所示:

#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
#include <fstream>
#include <string>
#include <cctype>
#include <numeric>
#include <iomanip>

using namespace std;

int main() {

    int digit = 1;
    string filename;
    //cout for getting user path
    //the compiler parses string literals differently so use a double backslash or a forward slash
    cout << "Enter the path of the data file, be sure to include extension." << endl;
    cout << "You can use either of the following:" << endl;
    cout << "A forwardslash or double backslash to separate each directory." << endl;
    getline(cin, filename);

    //gets file
    ifstream infile{filename};
    istream_iterator<char> infile_begin{ infile };
    istream_iterator<char> eof{};
    vector<char> file{ infile_begin, eof };

    for(int i =0; i < file.size(); i++){
    if(!isdigit(file[i])) {
        if(file[i] != ')') {
            file.erase(file.begin(),file.begin()+i);
        }
    }
    }
    copy(begin(file), end(file), ostream_iterator<char>(cout, " "));
    }

我不应该使用 vector.erase() 吗?我知道这段代码是不对的。如果是这样的话,更好的解决方案是什么?我知道在 C 中您可以将它写入内存并转到每个位置,这是更好的方法吗?

最佳答案

我会先将所有内容保存为字符串,准备字符串,然后将结果安全地 push_back 到 vector 中。 现在我使用 std::regex 来过滤你的文件。不过,这并不是最简单的。

#include <iostream>
#include <string>
#include <regex>
#include <fstream>

int main(){

    std::string file_name;
    std::cout << "Enter name/path of the txt file: ";
    std::getline(std::cin, file_name);
    std::ifstream file(file_name);

    std::vector<int> vec; //here save integers

    std::string text; //save current line here


    std::smatch match; //here the found "comment" get's saved, later to be removed from text

    std::regex remove("[\(\*]\.*[\*\)] *"); //the expression to search for
    //translation
    //     _[\(\*]   -> (*
    //     _\.*      -> any number of characters
    //     _[\*\)]   -> *)
    //     _ *       -> any number of whitespaces (important to cast to integer)..



    while (std::getline(file, text)){ //loop through all lines in file.txt

        if (std::regex_search(text, match, remove)){ //if a comment was found
            text.erase(text.begin(), text.begin() + match[0].length()); //remove the comment
        }

        if (!text.empty()) { //empty, line was a pure comment
            vec.push_back(std::stoi(text)); //else add integer to list
        }
    }


    std::cout << "The file contains:" << std::endl;
    for (int i = 0; i < vec.size(); i++){
        std::cout << vec.at(i) << std::endl;
    }

    return 0;
}

输出:

Enter name/path of the txt file: file.txt
The file contains:
58
63
70
56

当然,使用 std::stoi 只有在整数 之后没有字符时才有效。好吧,这只是一个想法,当然可以高度修改。

关于c++ - 从文件中删除注释并保留整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39373898/

有关c++ - 从文件中删除注释并保留整数的更多相关文章

  1. ruby-on-rails - 如何从 format.xml 中删除 <hash></hash> - 2

    我有一个对象has_many应呈现为xml的子对象。这不是问题。我的问题是我创建了一个Hash包含此数据,就像解析器需要它一样。但是rails自动将整个文件包含在.........我需要摆脱type="array"和我该如何处理?我没有在文档中找到任何内容。 最佳答案 我遇到了同样的问题;这是我的XML:我在用这个:entries.to_xml将散列数据转换为XML,但这会将条目的数据包装到中所以我修改了:entries.to_xml(root:"Contacts")但这仍然将转换后的XML包装在“联系人”中,将我的XML代码修改为

  2. ruby - 我可以使用 Ruby 从 CSV 中删除列吗? - 2

    查看Ruby的CSV库的文档,我非常确定这是可能且简单的。我只需要使用Ruby删除CSV文件的前三列,但我没有成功运行它。 最佳答案 csv_table=CSV.read(file_path_in,:headers=>true)csv_table.delete("header_name")csv_table.to_csv#=>ThenewCSVinstringformat检查CSV::Table文档:http://ruby-doc.org/stdlib-1.9.2/libdoc/csv/rdoc/CSV/Table.html

  3. ruby-on-rails - 如何优雅地重启 thin + nginx? - 2

    我的瘦服务器配置了nginx,我的ROR应用程序正在它们上运行。在我发布代码更新时运行thinrestart会给我的应用程序带来一些停机时间。我试图弄清楚如何优雅地重启正在运行的Thin实例,但找不到好的解决方案。有没有人能做到这一点? 最佳答案 #Restartjustthethinserverdescribedbythatconfigsudothin-C/etc/thin/mysite.ymlrestartNginx将继续运行并代理请求。如果您将Nginx设置为使用多个上游服务器,例如server{listen80;server

  4. ruby - 我可以使用 aws-sdk-ruby 在 AWS S3 上使用事务性文件删除/上传吗? - 2

    我发现ActiveRecord::Base.transaction在复杂方法中非常有效。我想知道是否可以在如下事务中从AWSS3上传/删除文件:S3Object.transactiondo#writeintofiles#raiseanexceptionend引发异常后,每个操作都应在S3上回滚。S3Object这可能吗?? 最佳答案 虽然S3API具有批量删除功能,但它不支持事务,因为每个删除操作都可以独立于其他操作成功/失败。该API不提供任何批量上传功能(通过PUT或POST),因此每个上传操作都是通过一个独立的API调用完成的

  5. ruby - 如何安全地删除文件? - 2

    在Ruby中是否有Gem或安全删除文件的方法?我想避免系统上可能不存在的外部程序。“安全删除”指的是覆盖文件内容。 最佳答案 如果您使用的是*nix,一个很好的方法是使用exec/open3/open4调用shred:`shred-fxuz#{filename}`http://www.gnu.org/s/coreutils/manual/html_node/shred-invocation.html检查这个类似的帖子:Writingafileshredderinpythonorruby?

  6. ruby-on-rails - 标准化文件名的字符串,删除重音和特殊字符 - 2

    我正在尝试找到一种方法来规范化字符串以将其作为文件名传递。到目前为止我有这个:my_string.mb_chars.normalize(:kd).gsub(/[^\x00-\x7F]/n,'').downcase.gsub(/[^a-z]/,'_')但第一个问题:-字符。我猜这个方法还有更多问题。我不控制名称,名称字符串可以有重音符、空格和特殊字符。我想删除所有这些,用相应的字母('é'=>'e')替换重音符号,并将其余的替换为'_'字符。名字是这样的:“Prélèvements-常规”“健康证”...我希望它们像一个没有空格/特殊字符的文件名:“prelevements_routin

  7. ruby - 使用 `+=` 和 `send` 方法 - 2

    如何将send与+=一起使用?a=20;a.send"+=",10undefinedmethod`+='for20:Fixnuma=20;a+=10=>30 最佳答案 恐怕你不能。+=不是方法,而是语法糖。参见http://www.ruby-doc.org/docs/ProgrammingRuby/html/tut_expressions.html它说Incommonwithmanyotherlanguages,Rubyhasasyntacticshortcut:a=a+2maybewrittenasa+=2.你能做的最好的事情是:

  8. ruby - 如何计算 Liquid 中的变量 +1 - 2

    我对如何计算通过{%assignvar=0%}赋值的变量加一完全感到困惑。这应该是最简单的任务。到目前为止,这是我尝试过的:{%assignamount=0%}{%forvariantinproduct.variants%}{%assignamount=amount+1%}{%endfor%}Amount:{{amount}}结果总是0。也许我忽略了一些明显的东西。也许有更好的方法。我想要存档的只是获取运行的迭代次数。 最佳答案 因为{{incrementamount}}将输出您的变量值并且不会影响{%assign%}定义的变量,我

  9. ruby - 在 Ruby 中将整数格式化为固定长度的字符串 - 2

    有没有一种简单的方法可以将给定的整数格式化为具有固定长度和前导零的字符串?#convertnumberstostringsoffixedlength3[1,12,123,1234].map{|e|???}=>["001","012","123","234"]我找到了解决方案,但也许还有更聪明的方法。format('%03d',e)[-3..-1] 最佳答案 如何使用%1000而不是进行字符串操作来获取最后三位数字?[1,12,123,1234].map{|e|format('%03d',e%1000)}更新:根据theTinMan的

  10. ruby-on-rails - 为什么在 Rails 5.1.1 中删除了 session 存储初始化程序 - 2

    我去了这个website查看Rails5.0.0和Rails5.1.1之间的区别为什么5.1.1不再包含:config/initializers/session_store.rb?谢谢 最佳答案 这是删除它的提交:Setupdefaultsessionstoreinternally,nolongerthroughanapplicationinitializer总而言之,新应用没有该初始化器,session存储默认设置为cookie存储。即与在该初始值设定项的生成版本中指定的值相同。 关于

随机推荐