[英]Segmentation fault (core dumped)
我有3個文件,即concat.cpp,concat.h和test4concat.cpp,在編譯和執行時出現以下錯誤。
輸入分割數:1分段故障(核心已轉儲)
它要求先拆分然后停止,因為我對cpp還是很陌生,因此我需要一些幫助。 謝謝
以下是3檔
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;
}
我遇到的問題:
輸入分割數:1分段故障(核心已轉儲)
在將數據讀入si,w和fid之前,您需要使用malloc(或用C ++編寫的新方法)分配內存。
si = new char[10];
w = new char[10];
fid = new char[10];
當然,您需要根據自己的需要修改字符數組的大小。
這將是在C ++中做到這一點的一種方法,避免了所有手動內存分配陷阱:
#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;
}
“輸入分割數:”;
所以你想要一個數字, int
。
int si;
cout << "Enter the number of splits: ";
cin >> si;
如果您真的想通讀指針,請先使用operator new
為它分配內存:
int main() {
char* pt = new char;
cin >> pt;
cout << (*pt);
delete pt;
return 0;
}
有一個std::string
類,它是一個C++
字符串,是std::basic_string
其中char
作為模板參數。 它很靈活,在這種情況下也可以使用:
#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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.