0

I'm fairly new to C++ and I can't seem to figure this out.

I get some weird output when running it. I am also trying to do this in the simplest way possible. How would I go about just printing the word in the suffix array and not all of the extra stuff. I have tried multiple ways to do this and they still show up.

    #include <iostream>
    #include <conio.h>
    #include <string>

    using namespace std;

    int main(){

        char word1[80];
        char word2[80];
        char suffix[80];

        cout << "Enter the first word: ";
        cin >> word1;

        cout << "Enter the first word: ";
        cin >> word1;

        int len1 = strlen(word1);
        int len2 = strlen(word2);

        while(len1 > 0 && len2 > 0 && word1[len1] == word2[len2]) {
            int k=0;
            suffix[k]=word1[len1];  

            k++;
            len1--;
            len2--;
        }



        for(int i=strlen(suffix);i>=0; i--){
            cout << suffix[i];
        }



        getch();
        return 0;
    }
4

2 回答 2

1

几件事:

  • 您应该更好地使用string而不是数组char。这样,您就不必担心内存问题。
  • 行 intk=0;应该在while.
  • 请记住,数组从 0 开始,因此从单词的长度中减去 1 并迭代 whilelen1 >= 0 && len2 >= 0
  • 使用字符串,您可以使用该方法substr(参考 此处)。

这是您的代码的修改版本:

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

int main() {
    string word1,word2,suffix;
    cout << "Enter the first word: ";
    cin >> word1;
    cout << "Enter the first word: ";
    cin >> word2;
    int len1 = word1.size()-1;
    int len2 = word2.size()-1;
    int k=0;
    while(len1 >= 0 && len2 >= 0 && word1[len1] == word2[len2]) {
        len1--;
        len2--;
        k++;
    }
    suffix=word1.substr(word1.size()-k,k);
    cout << suffix;
    getch();
    return 0;
}
于 2013-10-27T01:00:30.753 回答
1

我一直认为“最简单的方法”是使用别人的工作。这是编写利用标准库的程序的一种方法:

#include <algorithm>
#include <string>
#include <iostream>

std::string suffix(const std::string& a, const std::string& b) {
    size_t len = std::min(a.size(), b.size());
    auto its = std::mismatch(a.rbegin(), a.rbegin()+len, b.rbegin());
    return std::string(its.first.base(), a.end());

}

int main () {
    std::cout << suffix("December", "May") << "\n";
    std::cout << suffix("January", "February") << "\n";
    std::cout << suffix("April", "April") << "\n";
}
于 2013-10-27T01:02:31.837 回答