我有一些C ++代码,我从用户那里获取输入,将其添加到通过分隔符分割字符串的向量中,并且出于调试目的,打印向量的内容。但是,程序只打印矢量的第一个位置,然后打印其余的位置。 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;
}
输入&#34;退出1 2 3&#34;在终端返回:
exit /home/tay/Git/batch-interpreter: /home/tay/Git/batch-interpreter: /home/tay/Git/batch-interpreter: /home/tay/Git/batch-interpreter:
(输出中没有换行符) 为什么会这样?
答案 0 :(得分:2)
你说:
我有一些C ++代码,我从用户那里获取输入,将其添加到通过分隔符拆分字符串的向量中,并且出于调试目的,打印向量的内容。
你的代码确实:
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] << ' ';
}