我用结构体和指针做了一个程序。但由于某种原因,它无法正常工作。主要问题是,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/