How to insert data into the C++ string using the Geany IDE?

Asked

Viewed 71 times

-3

I’m studying String types in C. The most common was gets() however it was discontinued because of "buffer overflow". I would like to know what the equivalent function in IDE Geany to gets(). I’ve already tried gets_s() and also does not work. This code below always gives problem when compiling... He said that 'gets' was not declared in scope and suggests fgets(), but the function also does not work.

#include <stdio.h>
#include <stdlib.h>

int main () {

char name[50];

printf("Insira um nome: ");
gets(name);

printf("O nome inserido foi: %s \n", name);

system("pause");
return 0;
}

1 answer

-4

Using the stdio library means that you are trying to do something in c, but as your question refers to c++, I will use it to perform this process of getting the user’s character set.

#include <iostream>
int main(void){
char* name = new char[50];//tamanho do array para armazenar o nome
std::cout << "Digite um nome" << std::endl;//imprime o requerimento na tela
std::cin >> name;//obtém o conteúdo digitado no prompt
std::cout ​<< "O nome inserido foi " << name << std::endl; //imprime na tela
delete name;
}

"Std::" in the code indicates that I am using a namespace from the iostream library, but you can remove Std from the lines and include it at the top of the program using namespace Std

#include <iostream>
using namespace std;/*isso não causa problema na maioria dos casos, porém não é 
recomendado fazer isso*/
int main(void){
char* name = new char[50];//tamanho do array para armazenar o nome
cout << "Digite um nome" << endl;//imprime o requerimento na tela
cin >> name;//obtém o conteúdo digitado no prompt
cout ​<< "O nome inserido foi " << name << endl; //imprime na tela
delete name;
}

The "char*" represents a char pointer(character) the "new char[50]" allocates for this pointer 50 spaces, which was the size you placed

delete serves to de-allocate the pointer, as it is not deleted automatically as common array declarations

int nums[5]; /* array de 5 espaços que será excluído ao final do programa, forma 
mais comum e intuitiva/*
int* nums_a = new int[5]; /*mesma quantidade de espaços, porém devidamente alocados
e isso evita perda de memória quando o programa entra em stacks*/
delete nums_a; //de-aloca nums_a

if anyone notices anything wrong in my reply, say as soon as possible that I edit as soon as possible

  • 2

    Why not make an entire C++ code? And a modern code as recommended? This answer teaches you to do it wrong.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.