我正在编写一种迷你编程语言,目前正在编写我的第一个正确命令。我的命令称为“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/