我最終試圖編寫一個shell,所以我需要能夠解析命令。我試圖將每個單詞和特殊符號轉換爲令牌,而忽略空格。它適用於分隔令牌的字符是|但是隻要我使用單個空白字符,程序就會崩潰。這是爲什麼?閱讀空格解決Parser問題。爲什麼?
我是一名學生,我意識到我分離令牌的方式相當粗糙。我很抱歉。
#include <iostream>
#include <stdio.h>
#include <string>
#include <cctype>
using namespace std;
#define MAX_TOKENS 10
int main()
{
//input command for shell
string str;
string tokens[MAX_TOKENS] = { "0", "0", "0", "0", "0", "0", "0", "0", "0", "0" };
int token_index = 0;
int start_token = 0;
cout << "Welcome to the Shell: Please enter valid command: " << endl << endl;
cin >> str;
for (unsigned int index = 0; index < str.length(); index++)
{
//if were at end of the string, store the last token
if (index == (str.length() - 1)) tokens[token_index++] = str.substr(start_token, index - start_token + 1);
//if char is a whitespace store the token
else if (isspace(str.at(index)) && (index - start_token > 0))
{
tokens[token_index++] = str.substr(start_token, index - start_token);
start_token = index + 1;
}
//if next char is a special char - store the existing token, and save the special char
else if (str[index] == '|' || str[index] == '<' || str[index] == '>' || str[index] == '&')
{
//stores the token before our special character
if ((index - start_token != 0)) //this if stops special character from storing twice
{
//stores word before Special character
tokens[token_index++] = str.substr(start_token, index - start_token);
}
//stores the current special character
tokens[token_index++] = str[index];
if (isspace(str.at(index + 1))) start_token = index + 2;
else start_token = index + 1;
}
}
cout << endl << "Your tokens are: " << endl;
for (int i = 0; i < token_index; i++)
{
cout << i << " = " << tokens[i] << endl;
}
return 0;
}
你想看看那個:http://ericlippert.com/2014/03/05/how-to-debug-small-programs/ – Samuel
我認爲問題是'cin'輸入空格。你可能不得不使用'cin.getline()'。看看http://stackoverflow.com/questions/5838711/c-cin-input-with-spaces –
我的道歉,我會去找個橡皮鴨 – Nik