C++ 指针运行时错误

标签 c++ pointers for-loop runtime-error

我用结构体和指针做了一个程序。但由于某种原因,它无法正常工作。主要问题是,for-loop 不会按原样进行。如果你能解决这个问题会很有帮助

#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;
} 

最佳答案

您没有检查输入是否成功,也没有清除提取到 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);
}

如上所示,您还应该对 C++ 字符串使用 std::stoi

关于C++ 指针运行时错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21518444/

相关文章:

c++ - 双自由错误

c# - WPF C# 应用程序中的 C++ Dll

c++ - 为什么我的函数指针代码运行没有错误?

C - 指针和数组

c - for 循环在 C 中不能正确递增

c++ - RTKlib(C 库)与 QT(C++ 代码)

c++ - 在 C++ 或 Arduino 中,如何在函数中接受未知类型的参数?

C++双指针未知转换

Java - For 循环将无法完成,仅三个循环后就会崩溃

java - 对于 i0 变量