2016-10-17 60 views
-1

我試圖用用戶輸入字符串填充矢量,每次運行程序並調用函數時,無論輸入什麼內容,都會出現分段錯誤。我相當缺乏經驗,任何意見都表示讚賞。問題出在我的entry()函數中,每當我嘗試輸入一個字符串時,我的程序崩潰。我想知道爲什麼我每次都在同一位置看到分段錯誤。我錯過了明顯的東西嗎?向量回推中的分段錯誤

#include <iostream> 
#include <iomanip> 
#include <string> 
#include <vector> 
#include <algorithm> 

class Interface 
{ 
private: 
    std::vector<std::string> storage; 
    std::vector<bool> flag; 
int i; 
std::string temp; 
//temp 
int t; 
public: 
void entry(); 
void display(); 
void remove(); 
void complete(); 
void exit(); 
void recursiveBonus(); 

}; 

void Interface::entry() 
{ 
i = 0; 
do 
{ 
    std::cout << "Please enter a task:" << std::endl; 
    getline(std::cin, temp); 
    storage.push_back(temp); 
    flag.push_back(false); 
    i++; 
}while(storage[i] != " "); 
}; 
+2

'std :: vector storage(「」);'不能爲我編譯 – krzaq

+0

糟糕,抱歉!我一直在嘗試一堆東西來讓它起作用,認爲初始化可能會有所幫助,但我已經從中刪除了它,並在此處發佈的代碼中修復了它。運行中仍然存在故障。 –

+0

你的邏輯似乎有點有缺陷的循環。我假設你想在輸入空字符串時結束循環?那你應該檢查一下。即if(temp.empty()){break; }' –

回答

0

假設storageentry()進入時是空的:

考慮第一循環迭代。最初i == 0,然後你讀取一個字符串,並push_back它到storage。然後你增加i。現在i == 1。 然後檢查循環條件,其中storage[i],即storage[1]被訪問。索引1表示向量中的第二個元素,但您只插入了一個元素! 因此,您在此處有未定義的行爲,這可能是分段錯誤的原因。

此外,如果您想檢查輸入的最後一件東西是否爲空,則需要針對""而不是" "進行測試。後者不是一個空字符串,而是一個空格。查看問題的其他建議的意見。

+0

你們倆都有有用的反饋,謝謝!似乎我只是散佈了一些邏輯錯誤,需要重新審視。 –