Home > Back-end >  I can't print out sentence with 'cout' in c
I can't print out sentence with 'cout' in c

Time:03-20

first I not a native English speaker so if you find errors in my English ignore them,

below my code

#include <iostream>
#include <string>
#include <vector>


using namespace std;
 
//Globle variables
 
int Counter = 0 ;
vector<string> tasksList;
string task;
 
//functions
 
int AddingTasks(){ 
    cout<<"type your task here: ";
    cin>>task;
    tasksList[Counter-1].assign(task); // the "Counter-1" to set the index to zero because 'Counter' variable = 1  
    cout<<tasksList[Counter-1]<<"added "<<endl; // the problem is here it crash here it won't print out this Sentence 
  return 0;
}

int main(int argc, char const *argv[])
{
      tasksList.resize(Counter);
      int ChooseNum;
      cout<<"Mustafa ToDoList the best to do list ever!  "<<endl;
      cout<<"Choose: [1] add task [2] view tasks [3] edit task [4] delete task : ";
      cin>>ChooseNum;
      if (ChooseNum == 1)
      {
        Counter  ;
        AddingTasks();
      }
      // [2][3][4] are unnecessary now



   return 0;
}

I think there is no error in my code but there problem in 'AddingTasks()' function the program crash when it tries to print the task that's been added, I don't know why?

I am beginner in C .

CodePudding user response:

Change AddingTasks by:

int AddingTasks()
{
    cout << "type your task here: ";
    cin >> task;
    tasksList.push_back(task);
    cout << tasksList[tasksList.size() - 1] << " added " << endl;
    return 0;
}

What is happening is, you're trying to access an object that does not exist in the vector.

  • Related