簡體   English   中英

C ++使用命令行輸入txt文件,但無法打開文件

[英]C++ input txt file using command-line but failing opening the file

我正在嘗試使用命令行參數打開一個txt文件。 它總是無法打開文件。

我已經在互聯網上閱讀了所有答案,並且我的代碼與假定的代碼完全相同。

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <sstream>
#include <fstream>
#include <cstdbool>

using namespace ::std;
using std::printf;
using std::string;
using std::getline;


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

    fstream infile (argv[1]);

    if (infile.is_open() && infile.good()){
        string line="";
        while (getline(infile,line)){

            cout << line << endl;

        }
    }else{
        cout << "Failed to open file.. ";
    }


    return 0;

}



而且我一直在做g++ main.cpp -o newtest1 ./newtest1 < input.txt > output.txt

它看起來好像不讀input.txt但是寫在output.txt卻沒有任何問題。

你有兩個選擇

1)將輸入文件重定向到標准輸入

2)直接打開輸入文件

您的問題是同時進行

要么這樣做

1) ./newtest1 < input.txt

   string line="";
   while (getline(cin,line)){ // read from standard input

或這個

2) ./newtest1 input.txt

fstream infile (argv[1]);
if (infile.is_open() && infile.good()){
    string line="";
    while (getline(infile,line)){ // read from opened file

通常認為PS選項1更靈活。 因此,除非有充分的理由迫使用戶使用命名文件,否則它可能是最佳選擇。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM