我有一些 C++ 代码,我从用户那里获取输入,将其添加到一个 vector 中,按分隔符拆分字符串,并出于调试目的打印 vector 的内容。但是,程序只打印 vector 的第一个位置,其余的都不打印。 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”返回:
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] << ' ';
}
关于c++ - 无法正确打印 vector 内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30859820/