Reputation: 139
my code after compile crash when reaches to regex part:
I want check is any number exists in received string or no.
#include <iostream>
#include <regex>
using namespace std;
int main()
{
int in, count, rate;
char *w;
cin >> count;
for(in = 1; in < 5; in++) {
rate = 0;
cin >> w;
cout << "Case #";
cout << in;
cout << ":";
if (regex_match (std::string(w), regex("([0-9])")))
++rate;
cout << rate;
cout << endl;
}
return 0;
}
Upvotes: 1
Views: 1242
Reputation:
To avoid this kind of mistake in the feature, please enable warnings, i.e. -Wall
:
main.cpp:6:18: warning: 'w' is used uninitialized in this function [-Wuninitialized]
cin >> w;
Before using w
, you need to allocate memory for it. Generally in C-style code, you can either use an array with automatic storage:
char w[80]; // some arbitrary number guaranteed to be large enough to hold
// user input
or dynamic memory:
char* w = new char[80];
// ...
delete[] w;
As stated in another answer, it is more idiomatic to use std::string
in C++ as it handles the memory for you. This also avoids you creating all those unnecessary temporaries later in your code:
if (regex_match (std::string(w), regex("([0-9])")))
// ~~~~~~~~~~~~~~^
Upvotes: 3
Reputation: 5608
You are using a pointer with no allocated memory. This will crash your program. Just declare it as a string, and try to avoid naked pointers:
std::string w;
Upvotes: 7