2014-10-31 105 views
-1
#include <fstream> 
#include <iostream> 
#include <cstring> 
using namespace std; 


int main() 
{ 
     char filename[20] = "filename"; 
     char userInput; 

     ofstream myFile; 


     cout << "Enter filename: "; 
     cin.getline(filename, sizeof(filename)); 


     myFile.open(filename); 
     if(myFile.fail()) 
     { 
       cout << "Error opening file: " 
       << filename << "\n"; 
       return 1; 

     } 

     cout << "Add text to the file: "; 
     cin.get(userInput); 

     while(cin.good() && userInput) 
     { 
       myFile.put(userInput); 
       cin.get(userInput); 

     } 


     myFile.close(); 
     return 0; 



} 

我無法終止輸入而無需強制退出輸入(它仍然寫入文件)。用fstream和cstring寫入一個文件

這是我應該做的

接收輸入的來自用戶的線,然後輸出該 行指定的文件。這將繼續,直到用戶的行輸入 爲「-1」,其指示輸入的結束。

但是我不能解決-1部分。任何幫助將不勝感激一切似乎工作。

+0

,而'而(CIN >> userInput)' – Borgleader 2014-10-31 15:55:42

+0

是不工作。 – CryptiK 2014-10-31 16:02:19

+0

你正在返回'1',而不是'-1'。 – 0x499602D2 2014-10-31 16:08:01

回答

0

你讓事情比他們需要的複雜一點。爲什麼C字符串代替std::string,例如?使用正確的(標準提供的)類通常會導致更短,更簡單,更易於理解的代碼。嘗試這樣對於初學者:

int main() 
{ 
    std::string filename; 

    std::cout << "Enter filename" << std::endl; 
    std::cin >> filename; 

    std::ofstream file{filename}; 

    std::string line; 
    while (std::cin >> line) { 
     if (line == "-1") { 
      break; 
     } 
     file << line; 
    } 
} 
+0

我不得不選擇我們目前僅限於C字符串的課程。所以我不能使用一個字符串。 – CryptiK 2014-10-31 16:26:31

0

首先,該作業要求通過get()來讀取用戶,角色明智輸入不應該是功能使用。如你對收到的文件名,並使用一個比較函數來覈對-1使用成員函數getline()

for (char line[20]; std::cin.getline(line, sizeof line) && std::cin.gcount();) 
{ 
    if (strncmp(line, "-1", std::cin.gcount()) == 0) 
     break; 
    myFile.write(line, std::cin.gcount()); 
}