【问题标题】:C++ find words with first and last same letter and sort them in alphabetical orderC++ 查找第一个和最后一个字母相同的单词并按字母顺序对它们进行排序
【发布时间】:2023-03-21 05:03:01
【问题描述】:

我不能制作从文件中读取具有相同第一个字母和最后一个字母的单词(单词或长度没有限制)的程序。我使用类和对象,首先我无法阅读它们

#include <iostream>
#include <string>
#include <sstream>
#include <fstream>

using namespace std;
class Texts{

public:
    void Realding(string &All);
    void Searching(string &text, char *Word);
};
int main()
{

    Texts A;
    string Text; char word[40];
    A.Reading(Text);
    A.Searching(Text, word);
    system("PAUSE");


}

void Texts::Reading(string &All)
{
    string temp;
    ifstream read("Text.txt");
    while (getline(read, temp)) { All += temp; All += "\n"; }
    cout << All;

}

void Texts::Searching(string &text, char *Word)
{
    int i = 0;
    int j = 0;
    int letters = 0;
    int zodz = 0;
    int index = 0;
    while (1)
    {

        if (text[i] == ' ' || text[i] == '\0')
        {

            zodz++;
            if (text[0] == text[i - 1])
            {
                letters = j;
                for (int l = 0; l < letters; l++)
                {
                    //cout << text[l];
                }
                j = 0;
            }
            if (text[i + 1 - j] == text[i - 1])
            {
                letters = j;
                for (int l = i - j; l < letters; l++)
                {
                //  cout << text[l];
                }
                j = 0;
            }


        }

        if (text[i] == '\0') break;   
        else
        i++;                           
        j++;

    }
}

我无法从文件中正确读取它... Text.txt 看起来像

asdfa su egze hah ktis faf

以及如何稍后将具有第一个和最后一个相同字母的选定单词分配给数组,然后按字母顺序对它们进行排序。如果有人帮助我,谢谢。

【问题讨论】:

  • 是否需要使用类?我建议您在 main 函数或其他独立函数中执行此操作。它可以帮助你。
  • 这段代码无法编译;我怀疑这是你真正的代码。如果您不向我们展示您的真实代码,我们很难为您提供帮助。
  • 你应该一次处理一个单词;不要将它们全部读入一个字符串。
  • 有要求。哦,对不起,是的,有“阅读”和“搜索”功能。这是真实的代码。我会改变功能

标签: c++ class sorting object


【解决方案1】:

从文件中读取:

std::ifstream in(NameOfFile);
std::string word;

while (in >> word) //will stop when word can't be read. probably bad file or end of file
{
    // do something with word
}

查找首尾相同的单词

if (word.front() == word.back())
{
    // do something with word
}

请注意,这不处理带有大写字母的单词。它不会找到“妈妈”。它可能会因空话而崩溃。两者都有微不足道的修复。

给数组赋值

array[index++] == word;

这假设您要在插入数组后推进索引。请注意,如果数组过满,程序将表现不佳。如果任务允许,请考虑使用std::vector

对数组进行排序

std::sort(array, array + index);

这假设您被允许使用std::sort。同样,如果可能,请使用 std::vector 代替数组。在所有添加完成后,index 被假定为上面添加示例中 index 的值。如果您不允许使用std::sort,请提出另一个问题。这是一个冗长的话题。

【讨论】:

  • if (word.front() == word.back()) 可能会更清楚一些。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-05-21
  • 2022-12-10
  • 2016-02-08
  • 2021-02-18
  • 2020-05-21
  • 2016-11-25
  • 2015-01-18
相关资源
最近更新 更多