String output functions dilemma....

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • abhinuke
    New Member
    • May 2010
    • 23

    #1

    String output functions dilemma....

    OK,so I am working on this code in which I have to enter a string of length 20.After which I will enter a value of variable n resulting into output string which will start from index n upto white space or end of line.

    For ex:-if I enter string as John Smith and n=0 then it should output string as John and if n=2 then ohn.

    I tried to code this program in C/C++ but vain.Segmentati on faults is the only result that I am getting.

    Here is the code that I am working on.


    Code:
    #include <stdlib.h>
    #include<string>
    #include<iostream>
    #include<ctype.h>
    using namespace std;
    int main()
    {
        char a[20];
        int i,n;
        cout<<"Enter the desired string";
        cin.getline(a,20);
        cout<<"Enter string number\n";
        cin>>n;
        
        if(n==0)
        {
            cout.write(a,20);
        }
        else
        {
            
            cout<<"The required string is \n";
            i=n;
            while(a[i]!=' '||a[i]!='\0')
            {
                cout<<a[i];
                i++;
            }
        }
    
        return 0;
    }


    I am also confused between cin and cin.getline functions.Sugge stions,hints are welcome.

    Thanks in advance.
    Cheers.
  • Dheeraj Joshi
    Recognized Expert Top Contributor
    • Jul 2009
    • 1129

    #2
    Few modification for your while loop. Is it necessary to check a[i]!=' ' in this loop? Why you want it? And you must check the index has not crossed 20(Since you have a character array of size 20).

    Code:
    while((a[i]!=' '|| a[i]!='\0') && i < 20)
            {
                cout<<a[i];
                i++;
            }
    Regards
    Dheeraj Joshi

    Comment

    • abhinuke
      New Member
      • May 2010
      • 23

      #3
      Originally posted by dheerajjoshim
      Few modification for your while loop. Is it necessary to check a[i]!=' ' in this loop? Why you want it? And you must check the index has not crossed 20(Since you have a character array of size 20).

      Code:
      while((a[i]!=' '|| a[i]!='\0') && i < 20)
              {
                  cout<<a[i];
                  i++;
              }
      Regards
      Dheeraj Joshi
      @dheerajjoshim

      Thanks...that worked fine......Cant believe I am forgetting counters these days...

      Comment

      • Dheeraj Joshi
        Recognized Expert Top Contributor
        • Jul 2009
        • 1129

        #4
        Happens in software development environment. :)

        Regards
        Dheeraj Joshi

        Comment

        Working...