将文本文件传递给标准输入

时间:2014-09-23 01:46:38

标签: c++

以下代码是更大的翻译程序的一部分。下面的代码要求用户键入一行,而不是将其写回。有没有一种方法,而不是每次写一行,我可以在标准输入中传入一个完整的文件等'translate.txt',程序可以逐行写回来,并在行结束时产生错误到达了 ?

#include <iostream>
#include <string.h>
#include<stdio.h>
#include<fstream>
using namespace std;


using namespace std;


void PL() {

    char line[BUFSIZ];

    while( cin.good() ) {
         cout<<"Type line now"<<endl;
         cout<<"\n";
         cin.getline(line, sizeof(line));
         cout<<"\n"<<endl;
         string mystring = string(line);

        // supposed to Parsing string into words and translate// 
        //but just reading back input for now//

        cout<<"You typed:"<<mystring<<endl;
        cout<<"\n"<<endl;
    }

}

int main() {
    PL();
}

3 个答案:

答案 0 :(得分:2)

您希望有一种方法将文件传递给您的程序吗?

executable < file

答案 1 :(得分:1)

This code works well for me

void PL() {
   string line;

    while(cin) {
        cout<<"Type line now";
        if(std::getline(cin,line)) {
            // supposed to Parsing string into words and translate// 
            //but just reading back input for now//
            cout<<"You typed:"<<line<<endl;
        }
    }
}

请注意,stdin实际上已经从shell传递给程序,如上所述:

$ executable < file

如果你想传递从这个函数外部创建的任意类型的流,你需要像

这样的东西
void PL(std::istream& is) {
   string line;

    while(is) {
        cout<<"Type line now";
        if(std::getline(is,line)) {
            // supposed to Parsing string into words and translate// 
            //but just reading back input for now//
            cout<<"You typed:"<<line<<endl;
        }
    }
}

int main() {
    std::ifstream is("mytext.txt"); // hardcoded filename
    PL(is);
    return 0;
}

或者

int main(int argc, char* argv[]) {

    std::istream* input = &std::cin; // input is stdin by default
    if(argc > 1) {
        // A file name was give as argument, 
        // choose the file to read from
        input = new std::ifstream(argv[1]);
    }

    PL(*input);

    if(argc > 1) {
        // Clean up the allocated input instance
        delete input;
    }
    return 0;
}

肯定有更优雅的解决方案

并从命令行调用:

$ executable mytext.txt

答案 2 :(得分:0)

你的shell有办法在stdin上传递一个文件。例如,如果您使用的是兼容bourne的shell,则可以运行

translate < translate.txt

(假设您的程序被编译为名为translate的二进制文件)。这假设你想以交互方式启动程序,即从shell开始。

如果您想从您编写的其他程序自动生成此程序,则取决于您的操作系统。例如,在POSIX操作系统上,在分叉之后但在调用其中一个open族函数之前,您需要将dup2文件和STDIN_FILENO生成的文件描述符导入exec