What's wrong with my program [ is it wrong with pointer/ logic ]

# include<iostream.h>
# include<conio.h>

void main()
{
char name[80];
char *p;
int i;
cout<<"Enter your full address.: ";
cin.getline(name,80);
i=0;
p=name;
while(name[i]='\0')
{
if(*p!='.')
cout<<*p;
else
cout<<"\n" <<*p;
i++;
p++;
}

}


when i give address in one line as
xxx.c/o opp sai petrol pump.pune-24.
it should appear in following format
xxx.
c/o opp sai petrol pump.
pune-24.
but i got o/p in somewhat differnet format on screen
xxx
. c/o opp sai petrol pump
. pune-24
.
why this happened. let me know where is my mistake and why?
Last edited on
Firstly, is you're program C or C++? #include <iostream.h , #include <conio.h> are both old headers.

Secondly, I see no need for Conio to be in there as you haven't used any functions from its library.

Thirdly, main must always return an int - it must not be void. Some compliers do not even allow this to be compiled.

while(name[i]='\0') I believe this reads as: if name is null, execute this code.

Also, the reason you code it printing it in that format is that when the code reaches a '.' you are outputting a new line and then the '.' itself. You need to increment the pointer by one to move on to the next character so not to ouput the '.'.

Your code didn't seem to compile when I run it so I made my own that you may find useful. It doesn't contian pointers however:

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
#include <iostream>
#include <string>
using namespace std;

int main()
{
string name;
string *p;
int i;

cout<<"Enter your full address.: ";
getline(cin, name);

for(i=0; i<(name.length());i++)
{
  if(name[i]=='.')
   {
     cout << '\n';
     i++;
   }
  cout<<name[i];
}
cin.get();
return 0;
} 
Last edited on
Hy Kishor!
The problem seems to be in the while, not in the pointers.
You should have:while(name[i] != '\0' ). Here's the full code:
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
#include<iostream>

using namespace std;

int main()
{
  char name[80];
  char *p;
  int i;
  cout<<"Enter your full address.: ";
  cin.getline(name,80);
  i=0;
  p = name;

  while(name[i] != '\0' )
  {
    if(*p != '.')
      cout<<*p;
    else
      cout<<"\n" <<*p;
    i++;
    p++;
  }
  
  return 0;

}

But if i write abc.edg it outputs:

abc
.edg

so it's still not good enough.

This version seems to work how you want:
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
#include<iostream>

using namespace std;

int main()
{
  char name[80];
  char *p;
  int i;
  cout<<"Enter your full address.: ";
  cin.getline(name,80);
  i=0;
  p = name;

  while(name[i] != '\0' )
  {
    if(p[i] != '.')
      cout<<p[i];
    else
      cout<<'.'<<"\n";
    i++;
  }

  return 0;

}

If i type abc.efg it outputs:

abc.
efg
Oh sorry, i ddn't realise that you wanted the '.' - if you change your mind though then you can do it how i said.
Topic archived. No new replies allowed.