Why Does My Program Keep Crashing (C++)? [closed] - c++

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I don't understand why this won't run properly in Visual Studio 2012
#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
char nullChar()
{
char ch;
int ran = (rand() % 52);
if (ran < 26)
{
ch = (char) ('a'+ ran);
}
else
{
ch = (char) ('A'+ ran - 26);
}
return ch;
}
int main(int argc, char *argv[])
{
cout << "Enter a string";
int nullNum = 0;
nullNum = atoi(argv[2]);
if (strcmp(argv[1], "-d") == 0)
{
int count = -1;
do
{
int c = cin.get();
count++;
if(count == nullNum)
{
cout.put(c);
count = -1;
}
} while (!cin.eof()) ;
}
if(strcmp(argv[1], "-e") == 0)
{
char c = cin.get();
while(!cin.eof())
{
for (int i = -1; i < (nullNum-1); ++i)
{
cout << nullChar();
}
cout << c;
c = cin.get();
}
}
}
The code compiles perfectly. I'm suspecting something in a loop but I can't figure it out. I also think it ran perfectly a few days ago but now it's not. Is that possible?

Im not sure if you passed a parameter. But aside from that you should always check argc before using argv[xyz]. My guess is you get a segfault, because there is no argv[1] and argv[2]

Related

Why does this programme output the wrong value of the string in main? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 28 days ago.
Improve this question
The following code outputs the correct string in the parameters function, but the incorrect string in main.
Obviously something is going wrong, but I can't see what it is. Thanks.
#include <iostream>
#include <string>
using namespace std;
typedef struct sim {
const char* dir;
} sim;
string convertToString(char* a)
{
string s(a);
return s;
}
int parameters(sim *sdata, char **argv, int argc){
char *filename;
string token;
string delimiter = "=";
size_t pos = 0;
string s;
for (int i = 0; i < argc; ++i){
s = convertToString(argv[i]);
while ((pos = s.find(delimiter)) != string::npos) {
token = s.substr(0, pos);
s.erase(0, pos + delimiter.length());
}
if(token == "-dir"){
sdata->dir = s.c_str();
cout << sdata->dir << endl;
}
}
}
int main(int argc, char** argv) {
sim * sdata = (sim*)malloc(sizeof(sim));
parameters(sdata, argv, argc);
cout << sdata->dir << endl;
free(sdata);
return 0;
}
I started the program with ./teststring -dir=/home/stephen and got:
/home/stephen
�a
I was expecting both outputs to be the same.
The program has undefined behavior.
The pointer sdata->dir will be invalid after exiting the function parameters because the object s will not be alive. It has only the block scope of the function.
Also use the operators new and delete instead of calling the C function malloc. So write
sim * sdata = new sim;
You could write within the function for example like
if ( token == "-dir" )
{
sdata->dir = new char[s.length() + 1 ];
strcpy( sdata->dir, s.c_str() );
cout << sdata->dir << endl;
}
else
{
sdata->dir = nullptr;
}
provided that the data member dir is declared without the qualifier const.
typedef struct sim {
char* dir;
} sim;
Also using the typedef specifier in the structure declaration is redundant in C++.
So in main you will need to write
delete [] sdata->dir;
delete sdata;

How can I erase my string way quicker [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 5 years ago.
Improve this question
I am supposed to write a program that takes in string like "pre#ogrann##mmink#g" and returns "programming", it is like your backspace button is broken and when you hit it you get '#' instead of erasing the char out, and I have to fix it. I have working code here under but it is way to slow, and I might have to deal with huge string, any suggestion how I could do it better/faster?
#include <string>
#include <iostream>
using namespace std;
int main() {
string str;
while(cin >> str) {
bool done = false;
while(!done) {
if((int)str.find('#')>-1) {
str.erase(str.find('#')-1, 2);
} else {
done = true;
}
}
cout << str << endl;
}
}
Here's how I would do it. I haven't tested it to see if it is actually faster, but as it has a complexity of O(N), I think it should be fast enough:
while (std::cin >> input) {
std::string result;
result.reserve(input.length());
for (auto ch : input) {
if (ch == '#') {
if (result.length() > 0)
result.pop_back();
continue;
}
result += ch;
}
std::cout << result << '\n';
}
#include <iostream>
#include <string>
using namespace std;
string s = "pre#ogrann##mmink#g";
int main() {
string out;
int len = s.length();
for (int i = 0; i < len; i++) {
if(s[i] == '#') {
s.erase(i-1,2);
len = s.length();
i -= 2;
}
}
cout << s;
return 0;
}
This produces a working output.

To check if a string has all Unique Characters in C++ [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Am trying to find If a string has all Unique characters and below is my code, But I get the error "invalid types 'char[int]' for array subscript" in the if statement of the function Unique char, can anyone tell me how to correct this
#include <iostream>
#include<cstring>
using namespace std;
bool unique_char(char);
int main()
{
char s;
bool check;
cout << "Enter any string" << endl;
cin>>s;
check = unique_char(s);
if(check)
cout<<"there are no duplicates";
else
cout<<"the string has duplicates";
return 0;
}
// The if statement in this section has the error
bool unique_char(char s)
{
bool check[256] = {false};
int i=0;
while (s != '\0')
{
if (check **[(int) s[i]]**)
return false;
else
{
check[(int) s[i]] = true;
i++;
}
}
}
You need to pass char array rather than a single char.
int main()
{
char s[1000]; // max input size or switch to std::string
bool check;
cout << "Enter any string" << endl;
cin>>s;
check = unique_char(s);
if(check)
cout<<"there are no duplicates";
else
cout<<"the string has duplicates";
return 0;
}
bool unique_char(char* s)
{
bool check[256] = {false};
int i=0;
while (s[i] != '\0')
{
if (check[(int) s[i]])
return false;
else
{
check[(int) s[i]] = true;
i++;
}
}
return true;
}

Segmentation fault, no matter on how i change the code C++ [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
this is my code
#include <unistd.h>
#include <sys/types.h>
#include <dirent.h>
#include <stdio.h>
#include <cstring>
#include <iostream>
using namespace std;
bool endsWith(string const &value, string const &ending)
{
if(value.length() >= ending.length())
{
return (value.compare(value.length() - ending.length(), ending.length(), ending) == 0);
}
return false;
}
void listdir(const char *directory, const char *extension)
{
DIR *dir;
struct dirent *entry;
if(!(dir = opendir(directory)))
{
return;
}
while(entry = readdir(dir))
{
if(entry->d_type == DT_DIR)
{
char path[1024];
int len = snprintf(path, sizeof(path)-1, "%s/%s", directory, entry->d_name);
path[len] = 0;
if(strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0)
{
listdir(path, extension);
}
}
else
{
string file = entry->d_name;
if(endsWith(file, strcat((char *) ".", extension)) || extension == "*")
{
printf("%s \n", entry->d_name);
}
}
}
closedir(dir);
}
int main(int count, char *parameters[])
{
const char *type = "*";
const char *path = ".";
if(count > 1)
{
path = parameters[1];
}
if(count > 2)
{
type = parameters[2];
}
if(count < 1 || count > 3)
{
return 0;
}
listdir(path, type);
return 0;
}
And no matter, what i am doing, i always receive segmentation fault.
Compiling it with g++ under debian is no problem, but running the application puts out always "Segmentation fault"
So what's the matter?
Your error lies in the line strcat((char *) ".", extension), where you try to write data to the memory underlying a string literal.
String literals are loaded into a read only memory segment and trying to write to that causes your segfault.
If you wish to use strcat, you have to provide a target buffer of sufficient size (which is not checked, so using strncat is often preferred). Since this size is undetermined at compile time, you are forced to compute the length of the two strings you wish to append to one another and allocate a buffer of sufficient size with new or malloc.
However, the easiest way of performing a string concatenation in C++ is to forget all about the C equivalents and simply use ::std::string like so:
::std::string s = "hello ";
s += "world";

last index of C-style string in C++ [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I tried to write lastindexOf function for my C++ class. After I was trying for 2 weeks, I still can't get it working.
At first , I was trying to follow the logic from this post: CString find the last entry , but since they use CString class instead of char class,I have no success to duplicate the code for char class. I also try the strstr, but I have no luck with that neither. I would appreciate any helps.
here is the code I have came up with so far :
#include
using namespace std;
int lastIndexOf(char *s, char target);
int main()
{
char input[50];
cin.getline(input, 50);
char h = h;
lastIndexOf(input, h);
return 0;
}
int lastIndexOf( char *s, char target)
{
int result = -1;
while (*s != '\0')
{
if (*s == target ){
return *s;
}}
return result;
}
Try this:
int lastIndexOf(const char * s, char target)
{
int ret = -1;
int curIdx = 0;
while(s[curIdx] != '\0')
{
if (s[curIdx] == target) ret = curIdx;
curIdx++;
}
return ret;
}