2011-03-28 104 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

你可能想讓你的標題更好地反映你的問題。此外,你應該澄清你的問題,這是不是很清楚你問什麼。 – 2011-03-28 07:28:36

+0

K done,Thanks :) – FuzionSki 2011-03-28 07:31:12

+2

問題是'cin >> y'只存儲用戶輸入的第一個單詞,提問者想知道如何在y中存儲整行,這樣'file < 2011-03-28 07:32:20

回答

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

重要的部分是:'getline(std :: cin,y);'而不是'cin >> y;'。 – 2011-03-28 07:37:07

+0

參考:http://www.cplusplus.com/reference/iostream/istream/getline/ – fretje 2011-03-28 07:38:10

+1

你還需要cin >> ws;否則getline將只讀一個新行 – hidayat 2011-03-28 07:39:44

54

代碼cin >> y;只用一個詞,而不是整個行讀取。爲了得到一個行,使用:

string response; 
getline(cin, response); 

然後response將包含整個行的內容。

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

您可以使用函數getline函數讀取,而不是逐字讀字的整條生產線。並且cin >> ws在那裏可以跳過空格。你可以在這裏找到一些細節: http://en.cppreference.com/w/cpp/io/manip/ws

+0

非常感謝您的建議,我編輯了答案。 – 2018-01-30 19:29:33