Error with gets() -S.O.S.

I can't find the error in my program, help me please.

The first time the program do what it has to do, but when I thell to repeat it
it doesen't do it correctly, please help.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <iostream>
using  namespace std;
#include <stdio.h>
#include <string.h>

void main()
{
	char frase[200];
	int longitud;
	char letra;
	int i,ii ;
	int conta;
	int option;

	while(1)
	{
		conta = 0;
		frase[200]=0;
		cout<<"1) Introduzca la frase: ";
		gets(frase);
		cout<<endl;
		longitud = strlen(frase);//optimiza el programa.
		cout<<"2) Introduzca la letra a comprobar: ";
		cin>>letra;
		for ( i = 0;i <longitud;i++)
		{
			if (frase[i] == letra) {conta += 1;}
		}
		cout<<"La letra sale "<<conta<<" veces en la frase.";
		cout<<endl;
		cout<<"┬┐Ahora que quiere hacer?";
		cout<<endl;
		cout<<"1) Repetir el programa"<<endl;
		cout<<"0) Salir"<<endl;
		cout<<"--> ";
		cin>>option;
		cout<<endl;
		if (option == 0){exit(0);}
		else
		{
			for ( ii = 0;ii <longitud;ii++)
			{
				frase[ii] = 0;
			}
		}


	}
}
I think that the error is with the line 20 because the second time the program doesn't read it.
put cin.ignore(); in line 47 :)
Chriscpp wrote:
put cin.ignore(); in line 47 :)

This won't solve the problem. You must put cin.ignore() after every cin >> whatever; statement.
@usandfriends
I put it only in line 47 and it works for me
You are the bests really!!!! My teacher doesn't tell me about cin.ignore() but I will use it all the time, thaks!!!

I put here the code, it works really well !!!!!!!!! =)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44

#include <iostream>
using  namespace std;
#include <stdio.h>
#include <string.h>

void main()
{
	char frase[200];
	int longitud;
	char letra;
	int i,ii ;
	int conta;
	int option;

	while(1)
	{
		conta = 0;
		frase[200]=0;
		cout<<"1) Introduzca la frase: ";
		gets(frase);
		cout<<endl;
		longitud = strlen(frase);//optimiza el programa.
		cout<<"2) Introduzca la letra a comprobar: ";
		cin>>letra;
		for ( i = 0;i <longitud;i++)
		{
			if (frase[i] == letra) {conta += 1;}
		}
		cout<<"La letra sale "<<conta<<" veces en la frase.";
		cout<<endl;
		cout<<"┬┐Ahora que quiere hacer?";
		cout<<endl;
		cout<<"1) Repetir el programa"<<endl;
		cout<<"0) Salir"<<endl;
		cout<<"--> ";
		cin>>option;
		cout<<endl;
		if (option == 0){exit(0);}else{system("cls"); }
		cin.ignore();///////////////////////////////////////////////////////////////

	}
}
Topic archived. No new replies allowed.