c++ - If 语句错误地识别括号中的空格

标签 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;
}

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

最佳答案

想想这行是做什么的

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

If 表示如果输入包含空格并且如果 i 等于 5 则输出错误。由于 i 循环遍历字符串的所有索引,这对于长度至少为 5 的任何 字符串都是正确的,它包含一个空格anywhere

我想你真正的意思是这个

if (input[5] == ' ')

但我不太确定。

关于c++ - If 语句错误地识别括号中的空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57083490/

相关文章:

c++ - 在 Linux 中从我的应用程序启动网页

c++ - 我的 OpenGL 位图程序崩溃了?

c# - 从 32 位更改为 64 位

c++ - Code Endless 写入文本文件的第一行

C++ 成员初始化和构造函数

c++ - 在cin之前打印 "cout"?

C++ 命名空间别名和前向声明

c++ - 如何 boost 我的项目?

c++ - 当我尝试在 main 中调用插入函数时,它没有取数字?

c++ - 对 vector 中的一个元素进行排序的最有效方法?