c++ - 尝试使用 cin 设置字符串问题的值时程序崩溃 >>

标签 c++ string cin

这是我以前从未见过的奇怪错误,也不知道如何解决。崩溃发生在

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/

相关文章:

string - 句子的词级编辑距离

C++ 四舍五入到小数点后两位

c++ - 无字母循环

c++ - 在 C++ 中使用 cin 时使用循环计数被忽略

c++ - 使用 Winsock、GetDIBits 和 SetDiBits 传输位图

c# - 如何用另一个文件中的字符替换一个文件中的字符

python - 在字符串/数组中存储多个函数值 (Python)

c++ - 移动窗口时发生堆栈溢出(C++、winapi)

vector 的 C++ vector

c++ - 如何重定向头文件(到库)以在实例化中包含一些代码?