C++从文件中读取数字

C++ read number from a file

本文关键字:读取 数字 文件 C++      更新时间:2023-10-16

我有这个程序:

#include <iostream>
#include <fstream>
using namespace std;
int main (int argc, char** argv)
{
    ifstream infile("argv[1]");
    int testNumber = 0;
    infile >> testNumber;
    cout << testNumber << 'n';
}

我用这个命令./program myfile.txt 运行它

myfile.txt包含一些由空格和新行分隔的整数

我希望程序输出文件中的第一个数字,但它总是打印0。我做错了什么?

ifstream infile("argv[1]");

查找名为argv[1]而非myfile.txt的文件。要使用程序参数,请删除引号:

ifstream infile(argv[1]);