一、错误描述

在学习C++字符串string类的时候,由于错误使用cin.getline()函数,导致程序异常终止,退出码-1073741819 (0xC0000005)。

二、出错代码

#include <string>
#include <iostream>
using namespace std;
int main()
{
    const char *sh = "abcdefg";
    char *sh2 = nullptr;
//    char sh2[100];
    cout << sh << endl;
    string str = "ABCDEFG";
    cout << str.size() << endl;
    cin.getline(sh2, 10);
//    cin.ignore();
    cout << sh2;  //提前终止
    return 0;
}

执行到cout << sh2语句时终止。

三、出错原因

字符串sh2的定义问题。getline()函数只接受类似char sh2[100]这样的字符串定义,不接受字符串指针作为参数。将上述代码改成:

#include <string>
#include <iostream>
using namespace std;
int main()
{
    const char *sh = "abcdefg";
//    char *sh2 = nullptr;
    char sh2[100];
    cout << sh << endl;
    string str = "ABCDEFG";
    cout << str.size() << endl;
    cin.getline(sh2, 10);
//    cin.ignore();
    cout << sh2;
    return 0;
}

程序正常运行。输出结果:
在这里插入图片描述

更多推荐