Reputation: 3
I have 3 files namely concat.cpp, concat.h and test4concat.cpp, when i compile and execute i get the following error.
Enter the number of splits: 1
Segmentation fault (core dumped)
It asks for the first split and then stops, since i am fairly new to cpp i would need some help on this. Thanks
Following are the 3 file
concat.cpp
#include <iostream>
#include <cstring>
#include <fstream>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "concat.h"
using namespace std;
char concat(char* si,char* w,char* fid)
{
strcat (si,w);
strcat (si,fid);
return 0;
}
concat.h
#ifndef TRY_H_INCLUDED
#define TRY_H_INCLUDED
char concat(char* si,char* w,char* fid);
#endif
test4concat.cpp
#include <iostream>
#include <cstring>
#include <fstream>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <concat.h>
using namespace std;
int main ()
{
char* si;
char* w;
char* fid;
cout << "Enter the number of splits: ";
cin >> si;
cout << "Enter the number of watchdogs: ";
cin >> w;
cout << "Enter the Fid: ";
cin >> fid;
concat(si, w, fid);
cout<<"\nThe string is "<< si <<endl;
}
Problem which i am encountering:
Enter the number of splits: 1 Segmentation fault (core dumped)
Upvotes: 0
Views: 1986
Reputation: 29724
"Enter the number of splits: ";
So you want a number, int
.
int si;
cout << "Enter the number of splits: ";
cin >> si;
If you really want to read through pointer, first allocate memory to it with operator new
:
int main() {
char* pt = new char;
cin >> pt;
cout << (*pt);
delete pt;
return 0;
}
There is a std::string
class being a C++
string of characters, a specialization of std::basic_string
with char
as a template parameter. It is flexible and may be used in this case as well:
#include <iostream>
#include <string>
int main ()
{
std::string si, w, fid;
std::cout << "Enter the number of splits: ";
std::cin >> si;
std::cout << "Enter the number of watchdogs: ";
std::cin >> w;
std::cout << "Enter the Fid: ";
std::cin >> fid;
si += w;
si += fid;
std::cout<<"\nThe string is "<< si << std::endl;
return 0;
}
Upvotes: 0
Reputation: 227370
This would be a way to do it in C++, avoiding all manual memory allocation pitfalls:
#include <iostream>
#include <string>
int main ()
{
std::string si, w, fid;
std::cout << "Enter the number of splits: ";
std::cin >> si;
std::cout << "Enter the number of watchdogs: ";
std::cin >> w;
std::cout << "Enter the Fid: ";
std::cin >> fid;
si += w;
si += fid;
std::cout<<"\nThe string is "<< si << std::endl;
}
Upvotes: 1
Reputation: 488
You need to allocate memory using malloc (or new as you are writing in C++) before reading data into si, w and fid.
si = new char[10];
w = new char[10];
fid = new char[10];
Of course you need to modify the sizes of the character arrays for your own requirements.
Upvotes: 2