C Добавление местоположений на диске в текстовый файл

#c #c 11

#c #c 11

Вопрос:

Я сам изучаю C , используя C Programming Мураха.

Я в главе 9, Как работать со структурами и перечислениями

Я пишу названия фильмов, год и звезды, указывающие, что я думаю о фильме.

Обычно файл выглядит следующим образом:

 Casablanca  1942    5
The Wizard of Oz    1932    5
Star Wars   1979    4
Nightmare on Elm Street 2005    4
Home Alone  1990    5
Home Alone 2    1992    4
Home Alone  1990    4
Home Alone 2 Lost In New York   1992    4
Home Alone 3    1997    3
Home Alone 4 - Taking Back The House    2002    2
Home Alone 5 -- The Holiday Heist   2012    2
Star Wars                            1977    4       
lone Wars                           2008    3       
Rogue 1:  A Star Wars Story          2016    4       
Star Wars Holiday Special           1978    3       
The Ewok Adventure                   1984    2       
Ewoks:  The Battle For Endor         1985    3  
  

Вид файла выглядит следующим образом:

 NUMBER    TITLE                                           YEAR    STARS   
    1         4022333968tCasablanca                           1942    5       
    2         4022333968tThe Wizard of Oz                     1932    5       
    3         4022333968tNightmare on Elm Street              2005    4       
    4         4022333968tHome Alone                           1990    5       
    5         4022333968tHome Alone 2                         1992    4       
    6         4022333968tHome Alone                           1990    4       
    7         4022333968tHome Alone 2 Lost In New York        1992    4       
    8         4022333968tHome Alone 3                         1997    3       
    9         4022333968tHome Alone 4 - Taking Back The House 2002    2       
    10        4022333968ttHome Alone 5 -- The Holiday Heist   2012    2       
    11        4022334496tStar Wars                            1977    4       
    12        4022334496tClone Wars                           2008    3       
    13        4022334496tRogue 1:  A Star Wars Story          2016    4       
    14        4022334496txStar Wars Holiday Special           1978    3       
    15        4022334496tThe Ewok Adventure                   1984    2       
    16        4022334496tEwoks:  The Battle For Endor         1985    3    
  

Откуда берутся цифры перед каждым заголовком?
Теперь файл выглядит следующим образом:

 4022333968tCasablanca   1942    5
4022333968tThe Wizard of Oz 1932    5
4022333968tNightmare on Elm Street  2005    4
4022333968tHome Alone   1990    5
4022333968tHome Alone 2 1992    4
4022333968tHome Alone   1990    4
4022333968tHome Alone 2 Lost In New York    1992    4
4022333968tHome Alone 3 1997    3
4022333968tHome Alone 4 - Taking Back The House 2002    2
4022333968ttHome Alone 5 -- The Holiday Heist   2012    2
4022334496tStar Wars    1977    4
4022334496tClone Wars   2008    3
4022334496tRogue 1:  A Star Wars Story  2016    4
4022334496txStar Wars Holiday Special   1978    3
4022334496tThe Ewok Adventure   1984    2
4022334496tEwoks:  The Battle For Endor 1985    3
  

Далее следует весь код.

Я внес некоторые изменения в код, я добавил возврат в меню отображения и тайм-аут в коде просмотра файла.

  #include <iostream>
    #include <fstream>
    #include <sstream>
    #include <iomanip>
    #include <string>
    #include <vector>
    #include <limits>
    
////////STriuvctires////////
struct Movie {
    unsigned int number;
    std::string title = " ";
    unsigned int year = 0;
    unsigned int stars = 0;
    bool equals(Movieamp;);
};

// member function declaration
// member function definition


 bool Movie::equals(Movieamp; to_compare) {
        return (title == to_compare.title amp;amp; year == to_compare.year);
    }

const std::string movies_file = "movies.txt";

void display_menu() {
    std::cout << "COMMANDSn"
    << "v - View Movie Listn"
    << "a - Add a movien"
    << "d - Delete a movien"
    << "x - Exitnn";
}

std::vector<Movie> read_movies_from_file (){
    std::vector<Movie> movies;
    std::ifstream input_file(movies_file);
    //Check that file is open
    if(input_file) {
        Movie movie; // declare a copy of the Movie structure
                     // to work with
        std::string line;  // string to hold movie information.
        while( getline(input_file, line)) {
            std::stringstream ss(line);       
            getline(ss,  movie.title, 't'); //Get the movie title   
            ss >> movie.year >> movie.stars;  // get year and stars
            movies.push_back(movie);
        }
        input_file.close();
    }
    return movies;
}


void write_movies_to_file(const std::vector<Movie>amp; movies){
    std::ofstream output_file(movies_file);
    if (output_file) { // The file opened successfully
        for (Movie movie:movies) {
            output_file << movie.number << 't'
            << movie.title << 't'
            << movie.year << 't'
            << movie.stars << 'n';
        }
        output_file.close();
    }
}


void view_movies(const std::vector<Movie>amp; movies) {
        int col_width = 8;
        std::cout <<std::left
        << std::setw(col_width/2) << " "
       << std::setw(col_width   2) << "NUMBER"
        << std::setw(col_width * 6) << "TITLE"
        << std::setw(col_width) << "YEAR"
        << std::setw(col_width) << "STARS" << std::endl;
        //------------------------------------//
    
        int number = 1;
    // loop trough the file line by line
        for( Movie movie : movies){       
            std::cout << std::left
            << std::setw(col_width/2) << " "
           << std::setw(col_width   2) << number
            << std::setw(col_width * 6) << movie.title
            << std::setw(col_width) << movie.year
            << std::setw(col_width) << movie.stars << std::endl;
              number; // increase the count
            
        }
        std::cout << std::endl;
    //Code I added to hold the file view until the username
    // is ready to move on.
        char exit = 'x';
        std::cout << "nPress 'x' to continue:  ";
        std::cin >> exit;
        while (exit != 'x') {
            std::cout << "nPlease press 'x' to return to the Menu Display:  ";
            std::cin >> exit;
        }
        std::cout << std::endl << std::endl << std::endl;
        display_menu();
    }

 

    Movie get_movie(){
        Movie movie;
        std::cout << "Title:  ";
        std::cin.ignore(1000, 'n');
        getline(std::cin, movie.title);
        std::cout << "Year:  ";
        std::cin >> movie.year;
        std::cout << "Stars:  (1-5):  ";
        std::cin >> movie.stars;
        return movie;
    }



void add_movie(std::vector<Movie>amp; movies) {
    Movie movie = get_movie();
 
    // Check if movie already exists
    bool already_exists = false;
    for (Movieamp; m: movies){
        if (m.equals(movie)) {
            already_exists = true;
            m.stars = movie.stars;
            break;
        }//ends if()
    } // ends for()
    
    if (already_exists) {
        write_movies_to_file(movies);
        std::cout << movie.title << " already exists and was update.nn";
    }
    else {
        movies.push_back(movie);
        write_movies_to_file(movies);
        std::cout << movie.title << " was added.nn";
    }
    display_menu();
}

int get_movie_number(const std::vector<Movie>amp; movies){
    std::cin.ignore(1000, 'n');
    int number;
    while (true) {
        std::cout << "Number:  ";
        std::cin >> number;
        if (number > 0  amp;amp; number <= movies.size()) {
            return number;
        }
        else {
            std::cout << "Invalid movie number.  Try again.n";
        }
    }
}



 *void delete_movie(std::vector<Movie>amp; movies){
        int number = get_movie_number(movies);
        
        int index = number - 1;
        Movie movie = movies[index];
        movies.erase(movies.begin()   index);
        write_movies_to_file(movies);
        std::cout << movie.title << " was deleted.nn";
        //-----------------//
       // Return to display menu
        display_menu();
    }*
  

Я не знаю, почему это происходит, и я ничего не могу найти об этом в Интернете.

Спасибо за вашу помощь.

Ответ №1:

Цифры и буква t берутся из output_file << movie.number << 't' . movie.number никогда не инициализируется и содержит случайный мусор.