簡體   English   中英

C ++用戶輸入到字符串數組無限循環

[英]C++ user input to string array infinite loop

我正在嘗試將用戶輸入字符串解析為數組。 Example: user inputs "hello to you" array[0]="hello" array[1]="to" array[2]="you'在提示用戶輸入一些單詞后,程序似乎無限循環。我也嘗試過使用向量,所以這可能是我在另一個領域的邏輯。當我談到C語言時,我非常生銹,所以請原諒我的無知,任何幫助將不勝感激!

#include <iostream>
#include <string>
#include <sstream>

using namespace std;

struct FATNode;
struct FileNode;
class FileList;

class FAT
{
    FATNode* head;

};

class FileList
{
    FileNode* head;

    //methods
    public: 
        int createfile()
        {
            string word[2];
            cout << "Please input file name, followed by file size: ";

            int i = 0;
            for (string input; cin >> input; i++)
                    word[i] = input;

            for(i=0; i<2; i++)
                cout << word[i] << ' ';
            return 0;
        }

};

struct FileNode
{
    string filename;
    int filesize;
    FAT t1;
    FileNode* next;
};

struct FATNode
{
    int sectornumber;
    FATNode* next;
};

main()
{
    FileList myFileSystem;
    char start;
    int cmd;
    bool cont = true;

    while(cont == true)
    {
        cout << "Initializing disk.\n" << "To access menu, type 'Y'. To exit, type 'N': ";
        cin >> start;

        if(start == 'y' || start == 'Y')
        {
            cout << "What command would you like to execute on the disk?" << endl;
            cout << "1. Format disk\n2. Create file\n3. Delete file\n";
            cout << "4. List\n5. Read file\n6. Overwrite file\n7. Append to file\n8. Disk status\nSelection: ";
            cin >> cmd; 

            switch(cmd)
            {   
                case 1 :
                    break;
                case 2 :
                        myFileSystem.createfile();
                    break; 
                default :
                        cout << "Invalid command" << endl;
            }
        }
        else if(start == 'n' || start == 'N')
        {
            cont = false;
        }
        else
        {
            cout << "Invalid input." << endl;
        }
    }
}

您的循環條件是cin >> input 該表達式返回cin ,可以將其隱式轉換為布爾值( http://en.cppreference.com/w/cpp/io/basic_ios/operator_bool )。 但是,只有在出現錯誤或到達文件末尾( EOF )時, cin才會變為false 您可以通過按Ctrl + D發出EOF信號。

還要注意,您正在使用固定大小的數組來存儲從用戶那里獲得的信息。 不好,因為如果用戶輸入兩個以上的單詞,則數組word將溢出。 那是不確定的行為。

如果您只想要一個文件名,然后是文件大小,為什么不只使用:

std::string filename;
std::size_t filesize;
std::cin >> filename >> filesize;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM