无法正确打印矢量内容

Cannot Properly Print Contents of Vector

我有一些 C++ 代码,我从用户那里获取输入,将其添加到一个向量中,用定界符分割字符串,并出于调试目的打印向量的内容。但是,该程序只打印向量的第一个位置,然后打印其余的 none。 main.cpp

#include <cstdlib>
#include <iostream>
#include <string>
#include <stdio.h>
#include <vector>

//Custom headers
#include "splitting_algorithm.hpp"
#include "mkdir.hpp"
#include "chdir.hpp"
#include "copy.hpp"

//Used to get and print the current working directory
#define GetCurrentDir getcwd

using namespace std;

int main(int argc, char* argv[])
{
    string command;

    //Gets current working directory
    char cCurrentPath[FILENAME_MAX];
    if (!GetCurrentDir(cCurrentPath, sizeof(cCurrentPath)))
    {
        return 1;
    }

    //Placeholder for arguments
    for(int i=1; i<argc; i++)
    {
        cout<<string(argv[i])<<endl;
    }

    //Begin REPL code
    while (true)
    {
        //Prints current working directory
        cout<<cCurrentPath<<": ";
        cin>>command;

        vector<string> tempCommand = strSplitter(command, " ");

        //Exit command
        if(string(tempCommand[0])=="exit")
        {
            for(int i=0; i<tempCommand.size(); ++i){
                cout << tempCommand[i] << ' ';
            }
        }
    }
    return 0;
}

splitting_algorithm.cpp

#include <string>
#include <vector>
using namespace std;

vector<string> strSplitter(string command, string delim)
{
    vector<string> commandVec;
    size_t pos = 0;
    string token;
    string delimiter = delim;

    while ((pos = command.find(delimiter)) != string::npos)
    {
        token = command.substr(0, pos);
        commandVec.push_back(token);
        command.erase(0, pos + delimiter.length());
    }
    commandVec.push_back(command);

    return commandVec;
}

正在终端中输入 "exit 1 2 3" returns:

exit /home/tay/Git/batch-interpreter: /home/tay/Git/batch-interpreter: /home/tay/Git/batch-interpreter: /home/tay/Git/batch-interpreter:

(输出中没有换行符) 为什么会出现这种情况?

你说:

I have some C++ code where I'm taking input from a user, adding it to a vector splitting the string by delimiter, and for debugging purposes, printing the vector's contents.

而您的代码:

while (true)
{
    //Prints current working directory
    cout<<cCurrentPath<<": ";

    ///
    /// This line of code reads only one token.
    /// It does not contain multiple tokens.
    /// Perhaps you meant to read an entire line.
    /// 
    cin>>command;

    vector<string> tempCommand = strSplitter(command, " ");

    //Exit command
    if(string(tempCommand[0])=="exit")
    {
        for(int i=0; i<tempCommand.size(); ++i){
            cout << tempCommand[i] << ' ';
        }
    }
}

换行

cin>>command;

std::getline(std::cin, command);

此外,为了使输出更清晰,添加一行以打印换行符。 添加

std::cout << std::endl;

紧接着

for(int i=0; i<tempCommand.size(); ++i){
    cout << tempCommand[i] << ' ';
}