уникальные слова из файла c ++ - PullRequest
0 голосов
/ 30 марта 2020

это были 3 дня, я просто не могу определить, что не так с программой, программа должна сравнивать слова по словам, вместо этого она сравнивает только символ с символом, это показывает, что если у меня есть такие слова, как (aaa bbb cc dd) результат он печатает ab, и это же файл предложений, если я поставлю абзацы, чтобы сравнить только несколько символов, пожалуйста, помогите мне

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

using namespace std;

int main()    
{
    ifstream myfile("unique.text");

    int count = 0;

    string temp;

    string a;    

    int i,j;

    while(getline(myfile,temp))
    {
        for(i=0 ; i < sizeof(temp); i++)
        {
            for(int j = 0; j < i; j++)
            {
                if (temp[i] == temp[j])
                    break;
            }   

            if (i == j)
                cout << temp [i] <<" , ";
        }

        myfile.close (); 
   }

Ответы [ 2 ]

0 голосов
/ 30 марта 2020

Итак, некоторые ошибки в вашем коде.

Смешивание символов и строк, закрытие файла во время l oop и сохранение последних слов.

Одна рекомендация. Прежде чем писать код, напишите комментарии о том, что вы хотите сделать.

То есть создать проект, прежде чем начинать кодировать. Это очень важно.

Для вашей проблемы в заголовке этой темы:

уникальные слова из файла c ++

Я подготовил 3 разные решения. Первый - это использование очень простых конструкций. Второй использует std::vector. И третье - это решение C ++, использующее библиотеку алгоритмов C ++.

Пожалуйста, смотрите:

Простой, но длинный

И не рекомендуется, потому что мы не должны использовать необработанные указатели для собственной памяти и не должен использовать new

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

const std::string fileName{ "unique.text" };


unsigned int numberOfWords() {

    // Here we will count the number of words in the file
    unsigned int counter = 0;

    // Open the file. File must not be already open
    std::ifstream sourceFileStream(fileName);

    // Check, if we could open the file
    if (sourceFileStream) {

        // Simply read all words and increment the counter
        std::string temp;
        while (sourceFileStream >> temp) ++counter;
    }
    else {
        // In case of problem
        std::cerr << "\nCould not open file '" << fileName << "'\n";
    }
    return counter;
}

int main() {

    // Get the number of words in the source file
    unsigned size = numberOfWords();

    // Allocate a dynamic array of strings. Size is the count of the words in the file
    // Including doubles. So we will waste a little bit of space
    std::string* words = new std::string[size+1];

    // Open the source file
    std::ifstream sourceFileStream(fileName);

    // Check, if it could be opened
    if (sourceFileStream) {

        // We will read first into a temporary variable
        std::string temp;
        // Her we will count number of the unique words
        unsigned int wordCounter = 0;

        // Read all words in the file
        while (sourceFileStream >> temp) {

            // We will search, if we have read alread the word before. We assume NO for the beginning
            bool wordIsAlreadyPresent = false;

            // Go through all alread read words, and check, if the just read word is already existing
            for (unsigned int i = 0; i < wordCounter; ++i) {

                // Check, if just read word is already in the word array
                if (temp == words[i]) {

                    // Yes it is, set flag, and stop the loop.
                    wordIsAlreadyPresent = true;
                    break;
                }
            }
            // if the word was not already there
            if (! wordIsAlreadyPresent) {
                // Then add the just read temporary word into our array
                words[wordCounter] = temp;

                // And increment the counter
                ++wordCounter;
            }
        }

        // Show all read unique words
        for (unsigned int i = 0; i < wordCounter; ++i) {
            std::cout << words[i] << "\n";
        }
    }
    else { // In case of error
        std::cerr << "\nCould not open file '" << fileName << "'\n";
    }
    delete[] words;
}

Использование вектора. Уже более компактный и лучше читаемый
#include <iostream>  
#include <fstream>
#include <string>
#include <vector>

const std::string fileName{ "unique.text" };

int main() {

    // Open the source file
    std::ifstream sourceFileStream(fileName);

    // Check, if the source file is oepen
    if (sourceFileStream) {

        // Temporary string for holding just read words
        std::string temp;

        // In this vector we will store all unique words
        std::vector<std::string> words;

        // Read all words from the source file
        while (sourceFileStream >> temp) {

            // We will search, if we have read alread the word before. We assume NO for the beginning
            bool wordIsAlreadyPresent = false;

            // Go through all alread read words, and check, if the just read word is already existing
            for (unsigned int i = 0; i < words.size(); ++i) {
                // Check, if just read word is already in the word vector
                if (temp == words[i]) {

                    // Yes it is, set flag, and stop the loop.
                    wordIsAlreadyPresent = true;
                    break;
                }
            }
            // if the word was not already there
            if (not wordIsAlreadyPresent) {

                // Then add the just read temporary word into our array
                words.push_back(temp);
            }
        }
        for (unsigned int i = 0; i < words.size(); ++i) {
            std::cout << words[i] << "\n";
        }
    }
    else {
        std::cerr << "\nCould not open file '" << fileName << "'\n";
    }
}

И 3., более продвинутый язык программирования C ++. Просто очень мало строк и элегантный код.

Но его слишком сложно понять для начинающих.

#include <iostream>
#include <fstream>
#include <set>
#include <string>
#include <iterator>
#include <algorithm>

const std::string fileName{ "unique.text" };

int main() {

    // Open the source file and check, if it could be opend and there is no failure
    if (std::ifstream sourceFileStream(fileName); sourceFileStream) {

        // Read all words (everything delimited by a white space) into a set
        std::set words(std::istream_iterator<std::string>(sourceFileStream), {});

        // Now we have a set with all unique words. Show this on the screen
        std::copy(words.begin(), words.end(), std::ostream_iterator<std::string>(std::cout, "\n"));
    }
    // If  we could not open the source file
    else {
        std::cerr << "\nCould not open file '" << fileName << "'\n";
    }
    return 0;
}
0 голосов
/ 30 марта 2020

У вас есть пара проблем

temp имеет тип string. sizeof - это не способ определения длины string (он используется для определения таких вещей, как количество байтов в int). Вы хотите:

temp.length()

Во-вторых, индексирование в строку (temp[n]) дает вам n-й символ, а не n-е слово.

Вы можете сделать getline разбить на слова, добавив третий параметр-разделитель:

getline (myfile, temp, ' '))
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...