Ir para conteúdo
Sharank

Strcat Function In C++

Recommended Posts

Strcat Function In C++

 

I'm new to C and C++ programming, can anyone give me a hint on what I'm doing wrong here. I'm trying to write to concat function that takes to pointers to chars and concatenates the second to the first. The code does do that, but the problem is that it adds a bunch of junk at the end.

 

For instance, when passing the arguments - "green" and "blue", the output will be "greenblue" plus a bunch of random characters. I also wrote the strlen function that strcat uses, which I will provide below it for reference. I'm using the online compiler at InterviewBit The exact instructions and specification is this:

 

int main(int argc, char** argv)

{

const int MAX = 100;

 

char s1[MAX];

char s2[MAX];

 

cout << "Enter your first string up to 99 characters. ";

cin.getline(s1, sizeof(s1));

int size_s1 = strlen(s1);

cout << "Length of first string is " << size_s1 << "\n";

 

cout << "Enter your second string up to 99 characters. ";

cin.getline(s2, sizeof(s2));

int size_s2 = strlen(s2);

cout << "Length of second string is " << size_s2 << "\n";

cout << " Now the first string will be concatenated with the second

string ";

char* a = strcat(s1,s2);

 

for(int i = 0; i<MAX; i++)

cout <<a;

 

// system("pause");

return 0;

}

 

//strcat function to contatenate two strings

char* strcat(char *__s1, const char *__s2)

{

int indexOfs1 = strlen(__s1);

int s2L = strlen(__s2);

cout <<s2L << "\n";

int indexOfs2 = 0;

do{

__s1[indexOfs1] = __s2[indexOfs2];

indexOfs1++;

indexOfs2++;

}while(indexOfs2 < s2L);

 

 

return __s1;

}

 

//Returns length of char array

size_t strlen(const char *__s)

{

int count = 0;

int i;

for (i = 0; __s != '\0'; i++)

count++;

return (count) / sizeof(__s[0]);

 

}

Compartilhar este post


Link para o post
Compartilhar em outros sites

This is a Portuguese site , better chances if you answer in our language.

[]´s

Compartilhar este post


Link para o post
Compartilhar em outros sites

#include <iostream>
#include <cstring>
using namespace std;

// Declare strcat and strlen functions before main
char* mystrcat(char* s1, const char* s2);
size_t mystrlen(const char* s);

int main(int argc, char** argv) {
    const int MAX = 100;

    char s1[MAX];
    char s2[MAX];

    cout << "Enter your first string up to 99 characters: ";
    cin.getline(s1, sizeof(s1));

    int size_s1 = strlen(s1);
    cout << "Length of first string is " << size_s1 << "\n";

    cout << "Enter your second string up to 99 characters: ";
    cin.getline(s2, sizeof(s2));

    int size_s2 = strlen(s2);
    cout << "Length of second string is " << size_s2 << "\n";

    cout << "Now the first string will be concatenated with the second string\n";
    char* a = mystrcat(s1, s2);

    // print the concatenated string
    cout << a << endl;

    // system("pause");
    return 0;
}

// strcat function to concatenate two strings
char* mystrcat(char* s1, const char* s2) {
    int indexOfs1 = strlen(s1);
    int s2L = strlen(s2);
    int indexOfs2 = 0;

    do {
        s1[indexOfs1] = s2[indexOfs2];
        indexOfs1++;
        indexOfs2++;
    } while (indexOfs2 < s2L);

    s1[indexOfs1] = '\0'; // add null terminator to the end of the concatenated string

    return s1;
}

// Returns length of char array
size_t mystrlen(const char* s) {
    int count = 0;
    int i;
    for (i = 0; s != '\0'; i++) {
        count++;
    }
    return count;
}

 

You can try this code, and or you can choose a different compiler to run the code. I found this post on the internet; here author listed many cpp compilers, chose any online compiler and run the code.

Compartilhar este post


Link para o post
Compartilhar em outros sites
Visitante
Este tópico está impedido de receber novos posts.

  • Conteúdo Similar

    • Por biza
      Ola
      Estou  a construir um datalogger em código C.Desta forma necessito passar os dados entre ficheiros. O meu problema está na inclusão de algumas variáveis no topo de um arquivo .txt onde os dados são salvos. Variáveis como tempo de data e hora, id do dispositivo e muito mais... Para isso preciso de ajuda, gostaria que os dados estivessem disponíveis para todos os arquivos, até aí é fácil, basta incluir a variável como extern, no arquivos *.h e incluí-lo em todos os outros que você deseja que a variável esteja disponível. mas como posso fazer para ter acesso a ele dentro do array que preciso?
      Exemplo: main.c
      #include "main.h" char dateTimeFormat[24]; void main(void){ dateTimeFormat = "22-02-22 13:23:04"; } main.h
      extern char dateTimeFormat[24];  
      teste.c
       
      #include "main.h" extern char dateTimeFormat[24]; /*Header .txt file initialization*/ volatile char headerFile[] ="\n\n" "# HEALT MONITORING SYSTEM \r\n" "# DEVELOPED: BIZA \r\n" "# VERSION: B \r\n" "# DATATIMECAPTURE:"+dateTimeFormat+ "\r\n" "# SAMPLINGFREQUENCY: 500 \r\n" "# SAMPLECHANNELS: 1 2 3 4 5 6 7 8 \r\n" "# SAMPLINGRESULUTION: 24 \r\n" "# IDDEVICE: HEALTHY \r\n" "# ENDOFHEADER  
      Como posso incluir a variável "dateTimeFormat" dentro do headerFile como descrevi acima?
       
    • Por oromotoceu
      #include <stdio.h>
      #include <stdlib.h>
      #define MAXTAM 1000
      int Frente, Tras, Lista[MAXTAM];
      void Lista_Construtor(){
      Frente=0;
      Tras=-1;
      }
      int Lista_Vazia(){
      if(Tras==-1)
      return 1;
      else
      return 0;
      }
      int Lista_Cheia(){
      if(Tras==MAXTAM-1)
      return 1;
      else
      return 0;
      }
      int Lista_Tamanho(){
      return Tras+1;
      }
      int Lista_Inserir_Inicio(int Valor){
      if(Lista_Cheia()){
      return 0;
      }else{
      /*se quero inserir na posição 0,
      vou deslocar todos os elementos para frente*/
      for(int i=Tras+1;i>Frente;i--){
      Lista=Lista[i-1];
      }
      Lista[Frente]=Valor;
      Tras++;
      return 1;
        }
      }
      int Lista_Inserir_Fim(int Valor){
      if(Lista_Cheia()){
      return 0;
      }else{
      Tras++;
      Lista[Tras]=Valor;
      return 1;
        }
      }
      int Lista_Inserir(int Valor, int Posicao){
      if(Lista_Cheia()){
      return 0;
      }else{
      /* Para verificar se a posição
      está no meio da lista */
      if(Posicao>Frente && Posicao<Tras){
      for(int i=Tras+1;i>Posicao;i--){
      Lista=Lista[i-1];
      }
      Lista[Posicao]=Valor;
      Tras++;
      return 1;
      }else{ 
      return 0;
         }
        }
      }
      int Lista_Remover_Inicio(int *Valor){
      if(Lista_Vazia()){
      return 0;
      }else{
      *Valor =Lista[Frente];
      for(int i=Frente;i<Tras;i++){
      Lista=Lista[i+1];
         }
      Tras--;
        }
      }
      int Lista_Remover_Fim(int *Valor){
      if(Lista_Vazia()){
      return 0;
      }else{
      *Valor=Lista[Tras];
      Tras--;
      return 1;
        }
      }
      int Lista_Remover(int *Valor, int Posicao){
      if(Lista_Vazia()){
      return 0;
      }else{
      if(Posicao>Frente && Posicao<Tras){
      *Valor=Lista[Posicao];
      for(int i=Posicao;i<Tras;i++){
      Lista=Lista[i+1];
      }
      Tras--;
      return 1;
         }
        }
      }
      int Lista_Get_toda(int *Valor){
      if(Lista_Vazia()){
      return 0;
      }else{
      *Valor=Lista[Frente];
      return 1;
        }
      }
      int Lista_Get_inicio(int *Valor){
      if(Lista_Vazia()){
      return 0;
      }else{
      *Valor=Lista[Frente];
      return 1;
        }
      }
      int Lista_Get_Fim(int *Valor){
      if(Lista_Vazia()){
      return 0;
      }else{
      *Valor=Lista[Tras];
      return 1;
        }
      }
      int Lista_Busca_Valor(int Valor, int *Posicao){
      int i;
      if(Lista_Vazia()){
      return 0;
      }else{
      for(i=Frente;i<Tras;i++){
      if(Lista==Valor){
      break;
        }
      }
      if(i==Tras){
      return 0;
      }else{
      *Posicao=i; 
      return 1;
         }
        }
      }
      int Lista_Busca_Posicao(int *Valor, int Posicao){
      if(Lista_Vazia()){
      return 0;
      }else{
      if(Posicao>Frente && Posicao<Tras){
      *Valor=Lista[Posicao];
      return 1;
      }else{
      return 0;
         }
        }
      }
      int main(){
      int i,Valor,op=0,pos;
      Lista_Construtor();
      while(op!=12){
      printf("*** Menu de opções ***\n");
      printf("1-Inserir início\n");
      printf("2-Inserir fim\n");
      printf("3-Inserir meio\n");
      printf("4-Excluir início\n");
      printf("5-Excluir fim\n");
      printf("6-Excluir meio\n");
      printf("7-Mostrar toda lista\n");
      printf("8-Mostrar primeiro item da lista\n");
      printf("9-Mostrar último item da lista\n");
      printf("10-Mostrar a posição de um item da lista\n");
      printf("11-Mostrar o valor de uma posição\n");
      printf("12-Sair\n");
      printf("Escolha uma opção: ");
      scanf("%d", &op);
      switch(op){
          case 1:
              printf("Digite o valor a ser inserido: ");
              scanf("%d", &Valor);
              Lista_Inserir_Inicio(Valor);
              break;
          case 2:
              printf("Digite o valor a ser inserido: ");
              scanf("%d", &Valor);
              Lista_Inserir_fim(Valor);
              break;
            case 3:
              printf("Digite o valor a ser inserido: ");
              scanf("%d", &Valor);
              printf("Digite a posição que deseja inserir: ");
              scanf("%d", &pos);
              Lista_ Inserir_meio(int Valor, pos); 
              break;
            case 4:
              printf("Digite a remoção do início: ");
              scanf("%d", &*Valor);
              Lista_ Excluir_inicio(*Valor); 
              break;
              case 5:
              printf("Digite a remoção do fim: ");
              scanf("%d", &*Valor);
              Lista_ Excluir_fim(*Valor); 
              break;
              case 6:
              printf("Digite a remoção do meio: ");
              scanf("%d", &Valor);
              printf("Digite a posição que deseja remover: ");
              scanf("%d", &*Posicao);
              Lista_ Excluir_meio(intValor, * pos); 
              break;
               case 7:
              printf("Digite ao a mostrar toda lista: ");
              scanf("%d", &Valor);
              Lista_ mostrar_toda_lista(Valor);
              break;
             case 8:
              printf("Digite ao a mostrar primeiro item da lista: ");
              scanf("%d", &*Valor);
              Lista_ mostrar_primeiro_item_da_lista(*Valor);
              break;
             case 9:
              printf("Digite ao a mostrar último item da lista: ");
              scanf("%d", &*Valor);
              Lista_ mostrar_ultimo_item_da_lista(*Valor);
              break;
              case 10:
              printf("Digite ao a mostrar a posição de um item da lista: ");
              scanf("%d", &Valor);
              printf("Digite a posição que deseja mostrar na lista: ");
              scanf("%d", &* pos);
              Lista_ mostrar_posicao_de_um_item_da_lista(intValor, *pos);
              break;
              case 11:
              printf("Digite ao a mostrar o valor de uma posição: ");
              scanf("%d", &*Valor
              printf("Digite a posição que deseja mostrar no valor: ");
              scanf("%d", &pos);
              Lista_ mostrar_posicao_de_um_valor_da_lista(int*Valor, pos);
              break;
              case 12:
              default:
              printf("Valor Invalido!\n");
              system("PAUSE");
               }
         }
       return 0;
      }
    • Por oromotoceu
      bom dia pode me ajudar nessa questão por favor
      O programa deverá trabalhar dados de um veículo, onde será armazenado, Nome do proprietário, placa do carro, modelo do carro e preço do carro.
      O programa deve ter as seguintes opções:
      Inserir dados (todos os dados sugeridos no enunciado acima).
      Excluir um Carro específico com a busca pela placa.
      Editar dados de um Carro com a busca pela placa.
      Consultar carro por Placa.
      Exibir todos os dados cadastrados.
      Finalizar programa.
      A opção exibir todos os dados, apresenta tudo que já foi cadastrado e está na memória.
       
    • Por TK_T
      olá sou iniciante consegui fazer um o código de um exercício só que quando eu peço o valor 12ab ele lê como numérica alguém pode me ajudar? 
      Exercício: Leia uma string e diga se a mesma é numérica (na base decimal) ou não.
      Ex.: "123" -> numérica
      "abc" -> não numérica
      "12ab" -> não numérica
      "12.34" -> numérica 
      #include <stdio.h> int main() { char Numero; printf("Digite Algo: "); scanf("%c", &Numero); if(Numero == '1' || Numero == '2' || Numero == '3' || Numero == '4' || Numero == '5' || Numero == '6' || Numero == '7' || Numero == '8' || Numero== '9' || Numero == '0') printf("\tNumérica...\n"); else printf("\tNão Numérica\n"); return 0; }  
    • Por cgm2k7
      Boa noite!
      Bom preciso de uma dica/ajuda em uma problema...
      tenho duas structs, LIST e NO.  lista duplamente encadeada.
      //insiro/crio 100.000 nos.
       
      struct no{ char *nome; char sexo; float nota; float media; int id; struct no *next, *prev; }; struct list{ long int size_list; struct no *begin, *end; }; typedef struct no NO; typedef struct list LIST; for(int y = 0; y < 100000; y++) inserir_inicio(*list); void CreateNo(NO **no) { *no = (NO*)calloc(1,sizeof(NO)); if (*no) { (*no)->nome = "cicero"; (*no)->sexo = 'M'; (*no)->nota = 0.0; (*no)->media = 1; (*no)->id++; (*no)->next = NULL; (*no)->prev = NULL; is_Ok = true; } else { printf("ERRO: Ao alocar memoria em 'void CreateNo(NO **no)'\n"); is_Ok = false; return; } } void inserir_inicio(LIST *list) { NO *no; CreateNo(&no); if (is_Ok) { no->next = list->begin; list->begin = no; list->size_list++; } } // destroy os nos void DestoyList(LIST **list) { if ((*list)->begin == NULL) { free(*list); printf("Lista vazia!\n\n"); } else { NO *p = (*list)->begin, *tmp = NULL; while (p != NULL) { tmp = p; p = p->next; /*tmp->nome = "0"; tmp->sexo = '\0'; tmp->id = 0; tmp->media = 0;*/ free(tmp); } free(p); (*list = NULL); } } o problema é o seguinte:
      quando inicio o aplicativo ele começão com 512kb, quando criando  100.000  na memoria heap, aumenta para mais ou menos uns 7,8mb, bom ate aqui tudo oks
      mas quando delete este nos com o free() esperava eu q retornasse para os mesmo 512kb inicias do aplicativo, mas isso não acontece, ele retorna para 1,3mb.
      minha pergunta é: porque não deleta tudo, já setei zeros e para todos os membros da struct no mas mesmo assim não deleta tudo.
      Se alguém poder meda da uma dica. OBS: não quero código  pronto eu quero apenas dicas se possível bem explicada porque sou meio novato em c kkk.
×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.