在C ++中从文件中读取整数和字符的混合

问题描述

|| 使用C ++读取文件时遇到一些麻烦。我只能读取整数或字母。但是我无法同时阅读例如10af,ff5a。我的程序如下:
int main(int argc,char *argv[]) {

if (argc < 2) {
    std::cerr << \"You should provide a file name.\" << std::endl;
    return -1;
}

std::ifstream input_file(argv[1]);
if (!input_file) {
    std::cerr << \"I can\'t read \" << argv[1] << \".\" << std::endl;
    return -1;
}

std::string line;
for (int line_no = 1; std::getline(input_file,line); ++line_no) {
    //std::cout << line << std::endl;

         -----------
    }
       return 0;
 }
因此,我想做的是,允许用户指定他要读取的输入文件,并且使用getline获取每一行。我可以使用令牌的方法只读取整数或字母。但是我看不懂两者的结合。如果我的输入文件是 2 1 89ab 8 2 16ff 读取此文件的最佳方法是什么? 在此先感谢您的帮助!     

解决方法

我将使用
std::stringstream
,并使用ѭ2,因为89ab和16ff看起来像十六进制数字。 应该看起来像这样:
std::string line;
for (int line_no = 1; std::getline(input_file,line); ++line_no)
{
    std::stringstream ss(line);
    int a,b,c;

    ss >> a;
    ss >> b;
    ss >> std::hex >> c;
 }
您需要
#include <sstream>
    ,使用
std::string s;
while (input_file >> s) {
  //add s to an array or process s
  ...
}
您可以读取类型为“ 6”的输入,该输入可以是数字和字母的任意组合。您不一定需要逐行读取输入,然后尝试解析它。 “ 7”运算符将空格和换行符视为定界符。     

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...