2011-03-28 15 views
14

ここに私の現在のC++コードがあります。私はどのようにのコード行を書くことを知っていると思います。まだcin.getline(y)か何か別のものを使用しますか?私はチェックしましたが、何も見つかりませんでした。 私はそれを実行すると、完璧に動作します。それ以外のタイプの文字はのように出力されます。これは私が助けが必要なものです。私はコードでそれを概説しました。cinを使ってユーザーから完全な行を読み取る方法は?

#include <iostream> 
#include <cstdlib> 
#include <cstring> 
#include <fstream> 

using namespace std; 

int main() 
{ 
    char x; 

    cout << "Would you like to write to a file?" << endl; 
    cin >> x; 
    if (x == 'y' || x == 'Y') 
    { 
     char y[3000]; 
     cout << "What would you like to write." << endl; 
     cin >> y; 
     ofstream file; 
     file.open("Characters.txt"); 
     file << strlen(y) << " Characters." << endl; 
     file << endl; 
     file << y; // <-- HERE How do i write the full line instead of one word 

     file.close(); 


     cout << "Done. \a" << endl; 
    } 
    else 
    { 
     cout << "K, Bye." << endl; 
    } 
} 
+3

あなたのタイトルをあなたの質問をより良く反映させたいかもしれません。また、あなたの質問を明確にする必要があります、それはあなたが求めているものは本当に明確ではありません。 –

+0

K done、Thanks :) – FuzionSki

+2

問題は 'cin >> y'はユーザが入力する行の最初の単語だけを格納しているので、askerはy行全体を格納する方法を知りたいので' file < は、フルラインをファイルに書き込みます。 –

答えて

9
#include <iostream> 
#include <cstdlib> 
#include <cstring> 
#include <fstream> 
#include <string> 

int main() 
{ 
    char write_to_file; 
    std::cout << "Would you like to write to a file?" << std::endl; 
    std::cin >> write_to_file; 
    std::cin >> std::ws; 
    if (write_to_file == 'y' || write_to_file == 'Y') 
    { 
     std::string str; 
     std::cout << "What would you like to write." << std::endl; 

     std::getline(std::cin, str); 
     std::ofstream file; 
     file.open("Characters.txt"); 
     file << str.size() << " Characters." << std::endl; 
     file << std::endl; 
     file << str; 

     file.close(); 

     std::cout << "Done. \a" << std::endl; 
    } 
    else 
     std::cout << "K, Bye." << std::endl; 
} 
+3

重要な部分は、 'cin >> y;'の代わりに 'getline(std :: cin、y);'です。 –

+0

参照:http://www.cplusplus.com/reference/iostream/istream/getline/ – fretje

+1

また、cin >> wsが必要です。そうでなければ、getlineは新しい行だけを読むでしょう。 – hidayat

54

cin >> y;は、1つの単語だけではなく、全体のラインで読み取るコードを支援するための

感謝。行を取得するには、使用:

string response; 
getline(cin, response); 

はその後 responseは、行全体の内容が含まれています。あなたは全体のラインの代わりに、単語単位で読みを読み取ること のgetline機能を使用することができます

0
string str; 
getline(cin, str); 
cin >> ws; 

。そしてcin >> wsは、空白を飛ばすためのものです。そして、ここでそれについていくつかの詳細を見つける: http://en.cppreference.com/w/cpp/io/manip/ws

+0

提案をありがとう、私は答えを編集しました。 –

関連する問題