程序的功能是在提取标点时验证字符串是否是回文。代码提取双引号和单引号,但我似乎无法弄清楚如何提取空格。当使用调试器中的空格观察数组值时,似乎字符串在插入空格的位置被截断。我从键盘输入ra da r,字符串的数组值是调试器监视列表中的ra。
#include "stdafx.h"
#include <iostream>
bool palindrome(char[], int);
int main()
{
using namespace std;
bool status;
int siz,i;
char strarry[20];
siz = 0;
cout << " enter string" << endl;
cin >> strarry;
for (i = 0; strarry[i] != '\0'; i++)
++siz;
status = palindrome(strarry, siz);
if (status)
cout << " the string is a palindrome" << endl;
else
cout << "not a palindrome" << endl;
cin.clear();
cin.ignore(255, '/n');
cin.get();
return 0;
}
bool palindrome(char arry[], int size)
{
int i, l;
char arryn, arrysize;
static bool search = false;
static bool match = false;
static bool found = false;
static int n = 0;
int end = size - 1;
if (search != true){
for (i = 0; i <= end; i++){
if ((arry[i] == ' ') || (arry[i] == '\'') || (arry[i] == '\"')){
if ((end - i) >= 1){
for (l = i; l <= end; l++)
arry[l] = arry[l + 1];
--end;
size = end;
}
else{
size= end - 1;
}
found = true;
}//end if
}// end for
if (found == false)
size = end;
search = true;
}//end if
if (((n - size) <= 1) && match )
return true;
else{
arryn = arry[n];
arrysize = arry[size];
if (arry[n] == arry[size]){
++n;
match = true;
return palindrome(arry, size - 1);
}
else{
match = false;
return false;
}//end else
}// end else
}
答案 0 :(得分:0)
代码的问题在于你正在使用:
cin >> strarry;
cin 认为空格,制表符,换行符等是终止字符,因此一旦遇到其中一个字符,它就会停止读取该行的其余部分。
解决方案是使用:
getline(cin, strarry);
这会将分隔符限制为换行符。
答案 1 :(得分:0)
getline
。当你执行cin >> strarry
时,它只能读取第一个空格。使用getline(cin,str)
解决此问题
第三点;首先修剪空白。如果你首先构造一个没有whitespce的新字符串,那么is-a-palindrome函数将方式更容易编写。你可以用擦除 - 移除习语和isspace
来做到这一点