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

Sis*_*sta 5 c++ file token getline

我在使用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;
 }
Run Code Online (Sandbox Code Playgroud)

所以我想要做的是,我允许用户指定他想要读取的输入文件,并且我使用getline来获取每一行.我可以使用令牌方法只读取整数或只读取字母.但我无法阅读两者兼而有之.如果我的输入文件是

2 1 89ab

8 2 16ff

阅读此文件的最佳方法是什么?

非常感谢您的帮助!

Pir*_*ooz 0

使用

std::string s;
while (input_file >> s) {
  //add s to an array or process s
  ...
}
Run Code Online (Sandbox Code Playgroud)

std::string您可以读取可以是数字和字母的任意组合的类型的输入。您不一定需要逐行读取输入,然后尝试解析它。>>运算符将空格和换行符视为分隔符。