尝试从字符串中删除空格时,s.erase不起作用

问题描述 投票:0回答:1

我试图从字符串中删除空格以验证Palindrome短语。我已经查找了其他方法,但是我的教授在我们的指示中直接复制并粘贴了删除空格循环,但我无法让它工作,他说他不希望我们上网寻求帮助。我试图从“太热,不能发出声音”这样的短语中删除空格来验证它。我可以让我的程序使用像“bob”这样的单词,而不是短语。

#include <iostream>
#include <cstring>
using namespace std;

int main()
{
char input[100];
cout << "Please enter a word/phrase: ";
cin >> input;

for (int i = 0; i < strlen(input); i++)
{

    while (s[i] == ' ')//getting "s" is undefined error
        s.erase(i,1);
}

int i = 0; 
int j = strlen(input)-1;
bool a = true;

    for (i = 0; i < j; i++)
    {
        if (input[i] != input[j])
        {
            a = false;
        }
        j--;
    }

    if(a)
    {
        cout << input << " is a Valid Palindrome." << endl;
    }
    else
    {
        cout<< input << " is not a Valid Palindrome." << endl;
    }

system("pause");
return 0;
}
c++ visual-c++
1个回答
0
投票

也许你没有复制临时变量's'的结果。因此,修改后的代码应为:

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <cstring>
using namespace std;

int main(int argc, char *argv[])
{
    char input[100];
    cout << "Please enter a word/phrase: ";
    fgets(input, 100, stdin);

    string s(input);    // define a temporary variable 's'
    int i = 0; 
    while (i < s.length())
    {
        if (s[i] == ' ' || s[i] == '\n')
        {
            s.erase(i, 1);      // erase from variable 's', other then 'input'
            continue;
        }
        i++;
    }

    // copy result from 's' to 'input'
    sprintf(input, "%s", s.c_str());

    int j = strlen(input) - 1;
    bool a = true;

    i = 0;
    for (i = 0; i < j; i++)
    {
        if (input[i] != input[j])
        {
            a = false;
        }
        j--;
    }

    if (a)
    {
        cout << input << " is a Valid Palindrome." << endl;
    }
    else
    {
        cout << input << " is not a Valid Palindrome." << endl;
    }

    system("pause");
    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.