【发布时间】:2015-06-16 05:58:43
【问题描述】:
我有一些 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;
}
分割算法.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:
(输出中没有换行符) 为什么会出现这种情况?
【问题讨论】:
-
如果您没有删除已读取的数据,您的
strSplitter算法会更有效。您可以使用command.find(delimiter, pos + 1)从该位置开始搜索。 -
真的吗?谢谢,我从来不知道我能做到这一点!
-
我应该把那行放在哪里,我应该替换
command.erase()吗? -
您可以完全删除
command.erase(通过扩展您可以将command作为常量引用传递)。在函数顶部添加size_t prev_pos = 0;,将条件替换为pos = command.find(delimiter, prev_pos + 1),并在循环内token = command.substr(prev_pos, pos);。而不是erase,只需执行prev_pos = pos;。这样你基本上会走过整个字符串,拿起标记。 -
你来了,比预期的要复杂一点;)ideone.com/E0aJS5
标签: c++ arrays string vector segmentation-fault