簡體   English   中英

如何調整代碼以確保我的迭代器代碼接受用戶輸入?

[英]How can I adjust my code to make sure that my iterator code accepts user input?

我試圖理解為什么我的迭代器代碼不會打印正確的語句,即使我將正確的變量傳遞給它。 我還是C ++的新手,並且認為這可能是一個簡單的修復,但任何人都可以幫忙嗎?

Ps - 當我已經聲明了輸入時它工作正常但是當我希望代碼接受用戶輸入時它會給出不准確的結果

int main(){

list<string> personWords = {"Baxter","Nao","Jane"};
list <string> actionWords ={"recognise","detect","sees","pick","eats","lifts"};
list <string> directionWords = {"left","right","forwards","backwards"};
list <string> pronounWords = {"I","you","him","her"};
list <string> objectWords = {"apple","car","bus","diamond","atom","ball"};
list <string> textureWords = {"smooth","rough","shiny"};


string userInput;
cin >> userInput;
string userInputWords[3];
int counter = 0;
  for(int i = 0; i <= userInput.length(); i++){
    if (userInput[i] == ' '){

        counter++;}
    else{
        userInputWords[counter] += userInput[i];
    }
}
// The above for loop counts the number of words using the
// number of spaces inbetween the words and stores them in an 
// array

cout << userInputWords[0] << endl; // A check to see that correct word is being printed



list <string> ::iterator check1;
check1 = find(personWords.begin(),  personWords.end(), userInputWords[0]);

// searching for all of the person words


if(check1 != personWords.end()){ 
    cout << "Your word exists in Person Words list" << endl;
}
else{
    cout << "Your word does not exist in Person Words list" << endl;
}
}

這可能很容易解決

for(int i = 0; i <= userInput.length(); i++)
                 ^^

它應該是

for (int i = 0; i < userInput.length(); i++)

當它小於或等於時 ,它會添加用戶輸入的所有字符加一

這就是為什么std::find找不到你輸入的內容,因為它也抓住了這個詞之后的任何內容(可能是\\0 ,但是不要引用我的內容。)

暫無
暫無

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

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