Pointer Example: Some Problems Part 2

So heres my program:

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
50

#include<iostream>
#include<ctype.h>
#include<string.h>

/*
  Program to search for a given character inside a string and to print the string
  from the point of the match.
  the function should return nonzero if true,zero if false.
*/
using namespace std;

char *match(char,char*);

int main()
{
 char str[80],ch,*p;
 int i=0;
 
 cout<<"Enter the char to search: ";
 cin>>ch;
 cout<<endl;
 cout<<"Enter a string (max. 80 chars): ";
 cin.getline (str,80);
 cout<<endl;

 p=NULL;
 p=match(ch,str);

 if(!*p)
  {
   cout<<"Found the character !!!\n";
   for(char *count=p;*count!='\0';count++)
   cout<<*count<<endl;
  }
 else if(*p)
  cout<<"Not found !!!\n";

 cout<<"Thank you !!!\n";

 return 0;
}

char *match(char a,char *str)
{
 while((a!=*str) && (*str))
  str++;
 return (str);
}


The problem Im am having is tht cin.getline(str,80); wont input any text or whatsoever,and tht also after ive tried compiling it in various ways,like 3 times(std::cin.getline(..),etc,).I followed the tutorial here:
http://www.cplusplus.com/reference/istream/istream/getline/

But after tht the program doesnt compile and Im at a dead end.Pls help guys.
Thnx in advance.
Do you type 'Enter' after the char that you want?

The cin>>ch; will not remove the newline. The getline() immediately thinks that it has taken all it should, because it finds a newline.

Insert to line 26: if ( 0 == strlen( str ) ) cin.getline( str ,80 );
If and only if the first getline gets only empty string, then read second time


Then look at line 30. Your condition. That is false, if the pointer points to a non-null character.


Edit: That std::ws( std::cin ); below is a much better solution.
Last edited on
http://stackoverflow.com/questions/1744665/need-help-with-getline
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include<iostream>

int main() {
    int size = 80;
    char str[size], ch;
    cout << "Enter the char to search: ";
    cin >> ch;
    cin.clear();
    cout << "Enter a string (max. 80 chars): ";
    ws(cin);
    cin.getline(str, size);
    cout << endl;
    return 0;
}


Also if you are not just trying to play with pointers as an exercise I would look to using find. http://www.cplusplus.com/reference/string/string/find/
As is does exactly what you are trying to do.
Last edited on
Topic archived. No new replies allowed.