繁体   English   中英

从文本文件输入C ++命令行

[英]C++ command line input from a text file

我想从.txt文件中获取数字,并通过命令行将它们输入到如下例子的程序中。 我使用./program <input.txt运行exe。 但是它打印随机数。 我究竟做错了什么?

#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{
//print 1st number
cout << argv[1];
}
cout << argv[1];

相当于:

char* arg = argv[1];
cout << arg;

它只是将第一个参数的值打印到程序中

在您的情况下,您没有为程序提供参数。

当你使用时,

./program < input.txt 

input.ext的内容成为程序的stdin 您可以使用以下方法处理:

int c;
while ( (c = fgetc(stdin)) != EOF )
{
   fputc(c, stdout);
} 

如果您想继续使用C ++流,可以使用:

int c;
while ( (c = cin.get()) != EOF )
{
   cout.put(c);
} 

你可以这样做:

./program $(cat input.txt)

这样就可以了。

例如,如果input.txt的数字用空格分隔:

33 1212 1555

运行:

./program $(cat input.txt)  

将33打印到终端。

为了能够使用argv,需要提供参数,即

./program 23 45 67

对于./program <input.txt,您需要从cin(标准输入)读取。

#include <iostream>
using namespace std;
int n;
int main()
{
   cin >> n;
   cout << n;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM