lundi 27 mars 2017

c++ if(cin>>input) doesn't work properly in while loop

I'm new to c++ and I'm trying to solve the exercise 6 from chapter 4 out of Bjarne Stroustrups book "Programming Principles and Practise Using C++ and don't understand why my code doesn't work.

The exercise:

Make a vector holding the ten string values "zero", "one", ..., "nine". Use that in a program that converts a digit to its corresponding spelled-out value: e.g., the input 7 gives the output seven. Have the same program, using the same input loop, convert spelled-out numbers into their digit form; e.g., the input seven gives the output 7.

My loop only executes one time for a string and one time for an int, the loop seems to continue but it doesn't matter which input I'm giving, it doesn't do what it's supposed to do.

One time it worked for multiple int inputs, but only every second time. It's really weird and I don't know how to solve this in a different way.

It would be awesome if someone could help me out. (I'm also not a native speaker, so sorry, if there are some mistakes)

The library in this code is a library provided with the book, to make the beginning easier for us noobies I guess.

#include "std_lib_facilities.h"

int main()
{
   vector<string>s = {"zero","one","two","three","four","five","six","seven","eight","nine"};

   string input_string;
   int input_int;

   while(true)
   {
        if(cin>>input_string)
        {
             for(int i = 0; i<s.size(); i++)
             {
                  if(input_string == s[i])
                  {
                       cout<<input_string<<" = "<<i<<"\n";
                  }
             }
        }

        if(cin>>input_int)
        {
            cout<<input_int<<" = "<<s[input_int]<<"\n";
        }

    }

    return 0;
}

Aucun commentaire:

Enregistrer un commentaire