C ++ pointer execution error

I created a program using a structure and a pointer. But for some reason it is not working properly. The main problem is that the for-loop will not go as it would. It would be helpful if you could solve this problem.

#include <iostream>
#include <string>
#include <sstream>
using namespace std;

struct Book{
    string name;
    int release;
};

int main(){
    //local variable
    int i;
    string release_dte;
    int choice;
    //interface
    cout << "Welcome to Book Storage CPP" << endl;
    cout << "How many entries would you like to make: ";
    cin >> choice;
    Book* Issue = new Book[choice];
    //for handler
    for (i = 0; i < choice; i++){
        cout << "Book: ";
        getline(cin, Issue[i].name);
        cout << "Release Date: ";
        getline(cin, release_dte);
        Issue[i].release = atoi(release_dte.c_str());
    }
    cout << "These are your books" << endl;
    for ( i = 0; i < choice; i++){
        cout << "Book: " << Issue[i].name << " Release Date: " << Issue[i].release << endl;
    }
    system("pause");
    return 0;
} 
+4
source share
2 answers

You do not check if the input failed, and you do not clear the new line left after the extraction in choice:

if ((std::cout << "Book: "),
        std::getline(std::cin >> std::ws, Input[i].name) &&
    (std::cout << "Release Date: "),
        std::getline(std::cin >> std::ws, release_dte))
{
    Input[i].release = std::stoi(release_dte);
}

You should also use std::stoifor C ++ strings as shown above.

+2
source

, , . , getline() for , for \

cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n');

for (i = 0; i < choice; i++){
    cout << "Book: ";
    getline(cin, Issue[i].name);
    cout << "Release Date: ";
    getline(cin, release_dte);
    Issue[i].release = atoi(release_dte.c_str());
}

#include <iostream>
#include <string>
#include <sstream>
using namespace std;

struct Book{
  string name;
  int release;
};

int main(){
//local variable
int i;
string release_dte;
int choice;
//interface
cout << "Welcome to Book Storage CPP" << endl;
cout << "How many entries would you like to make: ";
cin >> choice;
Book* Issue = new Book[choice];

cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n');

//for handler
for (i = 0; i < choice; i++){
    cout << "Book: ";
    getline(cin, Issue[i].name);
    cout << "Release Date: ";
    getline(cin, release_dte);
    Issue[i].release = atoi(release_dte.c_str());
}
cout << "These are your books" << endl;
for ( i = 0; i < choice; i++){
    cout << "Book: " << Issue[i].name << " Release Date: " << Issue[i].release << endl;
}
system("pause");
return 0;

}

,

+2

Source: https://habr.com/ru/post/1524984/


All Articles