std::logic_error on Codeblocks

I am getting a std::logic_error when I try to run my code on Codeblocks

what<>: basic_string::_M_contruct null not valid

Can someone help?

Thanks

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

#include <iostream>
#include <cstdlib>
#include <string>
#include <vector>
#include <sstream>
#include <limits>
#include <stdio.h>


int main(){

    std::string sAge = 0;
    std::cout << "Enter your age: ";
    getline(std::cin, sAge);
    int nAge = std::stoi(sAge);

    if ((nAge >= 1) && (nAge <=18)){
            std::cout << "Important Birthday\n";
    } else if ((nAge == 21) || (nAge == 50)){
        std::cout << "Important Birthday\n";
    } else if ((nAge >= 65)) {
        std::cout << "Important Birthday\n";
    } else {
        std::cout << "Not an Important Birthday\n";
    }

    return 0;
}
 
The problem is on line 13.
 
std::string sAge = 0;

0 can be used as a null pointer constant (similar to nullptr) so this will call the const char* constructor that is normally used when constructing an std::string from a string literal (e.g. std::string str = "abc";). This constructor does not expect the pointer to be null so that is why it doesn't work.

The easiest way to create an empty string is to do nothing. The default constructor will automatically initialize the string to be empty.
 
std::string sAge; // creates an empty string 

Last edited on
Hi Peter,

Thanks very much. That worked!

Yusuf.
Topic archived. No new replies allowed.