Thread: c++ strings. input validation

  1. #1
    Registered User
    Join Date
    Aug 2004
    Posts
    10

    c++ strings. input validation

    I have this problem in my program! I need a function that fixes the input. If the string has white characters at the beginning. For example : if s=" hello" , i want to fix the string to be : "hello". I made this function fix_input but it seems to have a problem. Any ideas??

    Thank you
    Crashgr

    void fix_input(string &s)
    {
    string tmp;
    int i=0;

    while (s.at(i)==' ')
    i++;

    while(i<=s.length())
    {
    tmp+=s.at(i);
    i++;
    }

    s=tmp;
    }

    int main()
    {
    string input;

    getline(cin,input);

    if(!input.empty())
    {
    if (input.at(0)==' ')
    fix_input(input);

    cout<<input<<endl;
    }

    return 0;
    }

  2. #2
    Registered User jlou's Avatar
    Join Date
    Jul 2003
    Posts
    1,090
    What problem is it having? That information would help...

    If it is crashing or throwing an exception, it is because you go past the end of the string when you call at(i) with i = s.length(). Your loop should be while(i < s.length()) not while(i <= s.length()).

    Also, don't forget to include header files in your posted code, so it is easier for others to quickly copy your code and build it themselves.

  3. #3
    Registered User
    Join Date
    Aug 2004
    Posts
    10
    grrrrr!! I'm stupid!! Thank you jlou!! That was the problem!! And I swear that, this was the first thing i checked!! Thank you again.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. can someone help me with these errors please code included
    By geekrockergal in forum C Programming
    Replies: 7
    Last Post: 02-10-2009, 02:20 PM
  2. About aes
    By gumit in forum C Programming
    Replies: 13
    Last Post: 10-24-2006, 03:42 PM
  3. EOF messing up my input stream?
    By Decrypt in forum C++ Programming
    Replies: 4
    Last Post: 09-30-2005, 03:00 PM
  4. Input Validation Question
    By zackboll in forum C Programming
    Replies: 14
    Last Post: 10-12-2004, 12:05 AM
  5. Question about File Input
    By ChristianTool in forum C Programming
    Replies: 12
    Last Post: 04-25-2004, 02:40 PM