这是我以前从未见过的奇怪错误,也不知道如何解决。崩溃发生在
na = m
这是相关代码。有问题的行标有 *:
主要内容:
#include <cstdlib>
#include <iostream>
#include "stu.h"
#include <string>
#include <iomanip>
using namespace std;
int main(int argc, char *argv[])
{
stu stu;
int score[2];
std::string name;
std::cout <<"enter name:";
std::cin >> name;
//THIS IS AN EDIT IN AFTER SEEING THAT A IMPORTANT ERROR POINT WAS NOT SHOWN TO THE FIRST COUPLE REPLY
************************************************************
//THIS IS CAUSING THE PROBLEM WHEN I COMMENT IT OUT THE PROGRAM WORKS
std::cout << "enter score 1:";
std::cin >> score[0];
std::cout << "enter score 2:";
std::cin >> score[2];
std::cout << "enter score 3:";
std::cin >> score[3];
*************************************************************
stu.setname( name );
// ...
}
在stu.ccp
中:
void stu::setname(std::string m)
{
std::cout <<"1";//<--to find where the code was crashing
na = m; // *** the crash
std::cout <<"1";
}
在stu.hpp
中:
class stu
#include <string>
{
public:
stu();
void setname(std::string);
std::string getname();
void settest(int, int,int);
void display();
private:
std::string na;
int score[2];
};
最佳答案
当您定义 int score[2]
时,您会得到一个包含 2 个 int
的数组,并且有效的数组索引是 0..1
。
您稍后的代码写入数组的末尾并丢弃内存中的任何内容,在本例中为字符串对象 name
。
std::cout << "enter score 1:";
std::cin >> score[0];
std::cout << "enter score 2:";
std::cin >> score[2];
std::cout << "enter score 3:";
std::cin >> score[3];
最后两个数组引用不正确。
关于c++ - 尝试使用 cin 设置字符串问题的值时程序崩溃 >>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19574012/