Jump to content

How can i end a user string input loop?

- - - - -

  • Please log in to reply
5 replies to this topic

#1
IsNe

IsNe

    Newbie

  • Members
  • PipPip
  • 22 posts
i have the following function for reading strings into a vector:

istream& read(istream& in, vector<string>& word)
{
    string x;

    while (in >> x)
    word.push_back(x);

    in.clear();

    return in;
}

I'm just wondering if there is an easy way of ending this loop?
or do i have to make a word, like 'end' to stop the loop?

- Newb IsNe -

Edited by IsNe, 26 April 2010 - 12:20 PM.


#2
WingedPanther

WingedPanther

    A spammer's worst nightmare

  • Moderators
  • 16,831 posts
  • Location:Upstate, South Carolina
  • Programming Language:C, C++, PL/SQL, Delphi/Object Pascal, Pascal, Transact-SQL, Others
  • Learning:Java, C#, PHP, JavaScript, Lisp, Fortran, Haskell, Others
Generally, you need some keyword to end input.
Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog

#3
IsNe

IsNe

    Newbie

  • Members
  • PipPip
  • 22 posts
Thanks for the help ^^

- IsNe

#4
IsNe

IsNe

    Newbie

  • Members
  • PipPip
  • 22 posts
So this is how it ended up, if there is a simpler way, i would love to know ^^

istream& read(istream& in, vector<string>& word)
{
    string x;

    while (in >> x)
    {
        if (x == "end")
        {
            in.clear();
            return in;
        } else {
            word.push_back(x);
        }
    }
}


#5
marwex89

marwex89

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 10,720 posts
You could wait for a keypress, such as an "ESC". It would be simpler for the user, but harder to code, so it depends on what you mean by "simpler way". Also it would not be portable (read: would be platform dependent)

And it would perhaps be inconvenient if you are not reading user input from console.

Edited by marwex89, 27 April 2010 - 11:28 AM.

Hey! Check out my new Toyota keyboaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

#6
IsNe

IsNe

    Newbie

  • Members
  • PipPip
  • 22 posts
well, I'm not that far :P reading Accelerated C++
So if that function looks correct then I'm happy :D but often i do things a bit more complicated than they have to be, so just wondering you know ^^




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users