C ++指针运行时错误

时间:2014-02-03 01:20:15

标签: 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;
} 

2 个答案:

答案 0 :(得分:2)

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

您还应该将std::stoi用于C ++字符串,如上所示。

答案 1 :(得分:2)

我无法确切地推断出你指的是什么问题。但我的猜测是for循环中的getline()函数不能正常工作,我建议在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;

}

这将按预期工作