0

I wrote code that takes tasks from the user in store in the array, here is the code.

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


using namespace std;

//Globle variables

int Counter = 0 ;

vector<string> tasksList;

string task;

//function

void AddingTasks(){ // the problme is here
    cout<<"type your task here: ";
    cin>>task;
    tasksList.push_back(task);
    cout<<tasksList[tasksList.size()-1]<<" added "<<endl;
    //the console:
    // I type for example
    //type your task here: Buy electrician piano today.
    // you see the 'space' after 'buy' word and the first letter of 'electrician' the letter  'E'  the problem is about that 
}

int main(int argc, char const *argv[])
{
    tasksList.resize(Counter);

    char FuncationChoose;

    bool exit ;

    do // while do for repeating the code
    {
      cout<<"Mustafa ToDoList the best to do list ever!  "<<endl;
      cout<<"Choose: [1] add task [2] view tasks [3] edit task [4] delete task [E] Exit : ";
      cin>>FuncationChoose;

      if (FuncationChoose== '1')
      {
        AddingTasks();

        exit =false;
      }
      if (toupper(FuncationChoose) == 'E')
      {
        exit = true;
      }else{
        cout<<"error!."<<endl;
        exit = true;
      }

    } while ( exit == false );
      system("pause");
    return 0;
}

When I enter tasks with space and the word that begins with the letters of the list for example the letter 'E' it exit the code because 'E' for exiting the program, the user input in 'AddingTasks' affect the whole code.

Mustafa
  • 23
  • 4
  • As an aside `tasksList.back()` would be the more canonical way to access the last element of your vector – Cory Kramer Mar 21 '22 at 19:12
  • 2
    `cin>>task;` reads input until next space. All other input stays in the input stream. `cin>>FuncationChoose;` reads the first character after the space. [cppreference](https://en.cppreference.com/w/cpp/string/basic_string/operator_ltltgtgt) – jabaa Mar 21 '22 at 19:13
  • 4
    You want `std::getline` – ChrisMM Mar 21 '22 at 19:13
  • and judicious use of `istream::clear()` because extraction and `getline` differ in whether they leave the newline in the buffer or discard it – Ben Voigt Mar 21 '22 at 19:16
  • @BenVoigt I think you mean `istream::ignore()` not `istream::clear()`. – Remy Lebeau Mar 21 '22 at 19:34
  • @RemyLebeau: Yes, `ignore()` or sometimes both `ignore()` and `clear()` must be used together. – Ben Voigt Mar 21 '22 at 19:36

0 Answers0