2014-04-25 46 views
0

我在將用戶輸入保存到Txt文件時遇到問題。不知道我做錯了什麼;它不寫入文件:正在讀取和寫入文件流C++

void Menu::nowShowingDecisions() 
{ 
    switch (userInput) 
    { 
    case 1: 
     system("cls"); 
     xyPosition(0, 0); 
     CAtitleHeader(); 
     CAtitleMenu(); 
     getUserInput(); 
     CAtitleDecisions(); 

     break; 
     return; 

    case 2: 
    { 
     string userName; 
     string password; 
     { 
      ofstream outFile; 
      { 
       outFile.open("C:\\Test\\Test.txt"); 
       if (!outFile.good()) 
        cout << "File Could Not Be Opened." << endl; 
       else 
       { 
        cout << "Enter Username:"; 
        cin >> userName; 

        cout << "Enter Password:"; 
        cin >> password; 
        while (cin >> userName >> password) 
         outFile << userName << password << endl; 

        outFile.close(); 
       } 
      } 
     } 
     return; 
     { 
      const int COL_SZ = 10; 
      ifstream inFile; 
      inFile.open("C:\\Test\\Test.txt"); 
      if (!inFile.good()) 
       cout << "File could not be opened" << endl; 
      else 
      { 
       cout << left; 
       cout << "Movie Ticket Accounts" << endl; 
       cout << setw(COL_SZ) << "User Name" << setw(COL_SZ) << "Password" << endl; 
       while (inFile >> userName >> password) 
       { 
        cout << setw(COL_SZ) << userName << setw(COL_SZ) << 
        password << setw(COL_SZ) << endl; 
       } 

       inFile.close(); 
       return; 
      } 
     } 
    } 
    break; 
+0

請儘量保持你的Tab鍵是一致的。混淆標籤的代碼很難閱讀。 – user3553031

回答

0

在代碼

   cout << "Enter Username:"; 
       cin >> userName;    // BEING IGNORED 

       cout << "Enter Password:"; 
       cin >> password;    // BEING IGNORED 
       while (cin >> userName >> password) // THIS IS BEING SAVED> 
        outFile << userName << password << endl; 

你是不是寫的第一userNamepassword輸出文件此塊。

目前還不清楚您是否真的想要while環路。如果你想要寫出來只是第一個用戶名和密碼,則需要將其更改爲:

   cout << "Enter Username:"; 
       cin >> userName; 

       cout << "Enter Password:"; 
       cin >> password; 
       if (cin) 
        outFile << userName << password << endl; 
+0

非常感謝!對while循環感到困惑 – user3571613

0

讀取或寫入用C一個txt ++可以在這樣一種簡單的方式來完成。

//寫在一個文本文件

#include <iostream> 
#include <fstream> 

using namespace std; 

int main() 

{ 
    ofstream myfile ("example.txt"); 

    if (myfile.is_open()) 
{ 
    myfile << "This is a line.\n"; 
    myfile << "This is another line.\n"; 
    myfile.close(); 
} 
    else cout << "Unable to open file"; 
    return 0; 
} 

//讀取文本文件

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

int main() 

{ 
    string line; 
    ifstream myfile ("example.txt"); 
    if (myfile.is_open()) 
    { 
    while (getline (myfile,line)) 
    { 
     cout << line << '\n'; 
    } 
    myfile.close(); 
} 

    else cout << "Unable to open file"; 

return 0; 
}