regedit1818 2023-02-08 12:29 采纳率: 0%
浏览 241
已结题

char * [] 文本读取

请教一个问题:
char *name[]={"1","2"}
int Num ;

txt文件内容如下如下:
"1","2","3","4","5","6"

从文本文件读取这些数据,并读取到name中,并计数结果赋值到Num

  • 写回答

19条回答 默认 最新

  • 禹创 2023-02-08 17:24
    关注
    获得1.20元问题酬金

    利用本人珍藏字符串分解API,直接看代码:

    
    //////////////////////////////////
    #include <string>
    #include <iostream>
    #include <fstream>
    #include <streambuf>
    #include <memory>
    #include <vector>
    #include <map>
    
    using namespace std;
    
    /* 字符串分割 API */
    int split_s(const std::string& cont, std::vector<std::string>& result, char delim='\t') {
        std::size_t  new_tok = 0;
        std::size_t  cur_pos = 0;
        result.clear();
    
        for (; cur_pos < cont.size(); ++cur_pos) {
            if (cont[cur_pos] == delim) {
                std::string token = cont.substr(new_tok, (cur_pos - new_tok) );
                if (!token.empty()) {
                    result.push_back(token);
                }
                new_tok = cur_pos + 1;
            }
        }
    
        // 处理结尾
        if (new_tok < cont.size()) {
            std::string token = cont.substr(new_tok);
            if (!token.empty()) {
                result.push_back(token);
            }
        }
    
        return  result.size();
    }
    
    int main(int argc, char* argv[]) {
        string  fn = "datafile.txt"; // 默认文件名
        if (argc > 1) {
            fn = string(argv[1]); // 通过参数传入文件名
        }
        std::ifstream datf(fn); // 默认文件名
        if (!datf) {
            std::cout << "Open file FAILED!" << endl;        
            return -1;
        }
        /* 对于小文件,可以考虑一次性读入内存 */
        std::string name((std::istreambuf_iterator<char>(datf)),
                         std::istreambuf_iterator<char>());
        datf.close();
    
        std::vector<std::string> result;
        int num = split_s(name, result, ',');
    
        /* 根据需要输出结果 */
        cout << "num :=" << num << endl;
        cout << "name :=" << name << endl;
        return 0;
    }
    
    评论

报告相同问题?

问题事件

  • 系统已结题 2月16日
  • 专家修改了标签 2月12日
  • 创建了问题 2月8日

悬赏问题

  • ¥15 wegame打不开英雄联盟
  • ¥15 公司的电脑,win10系统自带远程协助,访问家里个人电脑,提示出现内部错误,各种常规的设置都已经尝试,感觉公司对此功能进行了限制(我们是集团公司)
  • ¥15 救!ENVI5.6深度学习初始化模型报错怎么办?
  • ¥30 eclipse开启服务后,网页无法打开
  • ¥30 雷达辐射源信号参考模型
  • ¥15 html+css+js如何实现这样子的效果?
  • ¥15 STM32单片机自主设计
  • ¥15 如何在node.js中或者java中给wav格式的音频编码成sil格式呢
  • ¥15 不小心不正规的开发公司导致不给我们y码,
  • ¥15 我的代码无法在vc++中运行呀,错误很多