2017-05-14 6 views
0

ファイルの名前を入力し、そのファイルが存在する場合はファイルのすべての内容を出力します。ファイル名を入力してテキストを読み取る

現在、非コメント化コードは、ユーザーが入力するファイルの名前を取ります。 example.txtを入力し、ファイルの最後の単語ではなく、ほとんどを出力します。私はこれを文字列を使って実装しようとしました(コメント付きコードは試行です)が、間違っています。

私は自動的にユーザー入力の末尾に.txtを追加することができますので、コンソールは次の質問をすることができますか? - 「ユーザー入力」の詳細については、 .TXT」ここ

がI'veが試したものです:

#include <iostream> 
#include <fstream> 
#include <cstdlib> 
#include <string> 
using namespace std; 

int main() { 


    char filename[50]; 
    //string getcontent; 
    ifstream name; 
    cin.getline(filename, 50); 
    name.open(filename); 

    if (!name.is_open()) { 
     exit(EXIT_FAILURE); 
    } 

    char word[50]; 
    name >> word; 
    while (name.good()) { 
     cout << word << " "; 
     name >> word; 
    } 

    //if (!name.is_open()) { 
     //while (! filename).eof()) 
     //{ 
      //getline(name, getcontent) 
      //cout << getcontent << endl; 
     //} 

     //exit(EXIT_FAILURE); //comes from cstdlib 
    //} 



    //} 



    system("pause"); 
    return 0; 
} 
+1

あなたは 'のstd :: STRING'を使用することができるときなぜあなたは' '[50]をchar型のファイル名を使用していますか? – InternetAussie

+1

同じことが 'char word [50]'にはありません。これはC++です。また、 'system(" pause ")'は移植性がないため、悪い習慣です。代わりに 'std :: cin.get()'を使用してください。 –

答えて

0
#include <iostream> 
#include <fstream> 
#include <cstdlib> 
#include <string> 
using namespace std; 

int main() { 

    string filename; 
    string getcontent; 
    ifstream name; 
    cin >> filename; 
    filename.append(".txt"); // add extension. 
    name.open(filename); 

    if (!name.is_open()) { 
     exit(EXIT_FAILURE); 
    } 

    while (true) 
    { 
     getline(name, getcontent); 
     if (name.eof()) break; 
     cout << getcontent << endl; 
    } 

    return 0; 
} 
+0

これはありがとう、私は今それを理解しています。しかし、私は何かの理由をコンソールに投稿されたテキストを取得していない?私のファイルは正しいディレクトリにあります –

+0

あなたはWindows上ですか?私はこれをLinuxでテストしました。出力を見ることができないようにコンソールがすぐに閉じることを意味しますか?もしそうなら、 'return 0'の前に' system( "pause");を入れます。 – Shibli

+0

はい私は窓に私は、私は "example"を入力し、私のディレクトリにexample.txtを持って、それをしました。これは「これはファイル内のテキストです」ではなく「続けるために任意のキーを押してください」と表示されます。私のディレクトリに存在しないファイルを開いた場合、プログラムは意図したとおりに終了します –

関連する問題