如果语句错误地识别括号中的空格

时间:2019-07-17 20:15:28

标签: c++

我正在编写一种小型编程语言,目前正在处理我的第一个正确命令。我的命令叫做'prout(“ Sample text”)'。当我的程序在prout单词的字母t和左括号之间看到一个空格时,它会输出意外的缩进错误,这应该发生了。不应发生的事情是识别用户想要输出的文本中的空格,并输出意外的缩进错误。有人知道如何实现一种阻止程序识别用户要输出的文本中的空格是意外的缩进错误的方法吗?

以下是当前输出:

>>> prout("Hello")
Hello
>>> prout ("Hello")
Error: Unexpected indent //That is supposed to happen
>>> prout("Hello I am a programmer!")
Error: Unexpected indent //That is the problem

我尝试使用.npos属性来过滤空格,但这没有用。

#include <iostream>
#include "printoutput.h"
#include "Line.h"

using namespace std;

void printoutput::print(string input) {
    int i = 0;
    int length = input.length();
    if (input.find('(') != input.npos && (input.find(')') != input.npos) && (input.find('\"') != input.npos)) {
        for (int i = 0; i <= input.length(); i++) {
            char letter = input[i];
            if (input.find(' ') != input.npos && (i == 5)) {
                cout << "Error: Unexpected indent";
                break;
            }
            if ((letter == 'p') && (i != 0) || (letter == 'r') && (i != 1) || (letter == 'o') && (i != 2) || (letter == 'u') && (i != 3) || (letter == 't') && (i != 4) || (letter == '(') && (i != 5) || (letter == '\"') && (i != 6 && i != input.length() - 2) || (letter == ')') && (i != length - 1)) {
                char inputletter = input[i];
                cout << inputletter;
            }
            else if ((i != 0 && (i != 1) && (i != 2) && (i != 3) && (i != 4) && (i != 5)) && (i != 6 && i != length - 2) && (i != length - 1)) {
                char inputletter = input[i];
                cout << inputletter;
            }
        }
    }
    if (input.find('\"') == input.npos) {
        cout << "Syntax error: Missing quotation marks";
    }
    else if (input.find('(') == input.npos || (input.find(')')) == input.npos) {
        cout << "Syntax error: Missing parenthesis";
    }
    cout << endl;
}

我希望输出显示用户想要输出的文本以及可能包含的空格。

1 个答案:

答案 0 :(得分:2)

考虑这一行的作用

if (input.find(' ') != input.npos && (i == 5)) {

If表示输入内容是否包含空格,并且i等于5时输出错误。由于i遍历字符串的所有索引,因此长度至少为5的 any 字符串都是正确的,其中包含空格 anywhere

我在想你真正的意思是

if (input[5] == ' ')

但我不太确定。