从向量获取值

obtaining values from a vector

本文关键字:获取 向量      更新时间:2023-10-16

我的代码在输入字符串后出现错误。 我需要有一个字符串输入(例如添加水果),它将通过"add"关键字放入我的向量中。但是当我也输入一个单词(例如打印)时,打印我的矢量中的元素。它行不通。有什么见解吗?

#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;

vector <string> separate(string str){
   string word = "";
   vector <string> v = {0,0};
   for (auto x : str)
   {
       if (x == ' ')
       {
           v[1] = word;
           word = "";
       }
       else
       {
           word = word + x;
       }
   }
    v[0] = word;
    return v;
}
int main(){

    string user_input, command, item;
    int cmds;
    vector <string> result;

    while (1){
        cout << "Enter a command: ";
        getline(cin, user_input);
        vector <string> arrcmd = separate(user_input);
        (arrcmd.size() == 1) ? (command = arrcmd[0]) : (command = arrcmd[1], item = arrcmd[0]);
        cout << arrcmd.size() << endl;
 /*       command = arrcmd[0], item = arrcmd[1];   */
        cout << command << " " << item << endl;

vector <string> v = {0,0};创建一个包含两个元素的向量。因此,separate总是返回大小为 2 的向量 - 它并不总是填充其第二个元素。

main尝试根据向量大小做出决策 - 但从未采用size() == 1路径。