Help for ToDoList Coding

Hi guys, I'm trying to make a To Do List. Which will ask the user about the number of tasks he wants to enter. Then he will be asked to enter the description. And at the end, it will display the tasks.
It runs well with the following coding. But when I use cin.get(), gets() or cin.getline() instead of cin >> at line 16, numbering at line 15 and 22 don't go well. I don't want to use cin >> as a description may include space character. Could anyone tell me why is this happening and what's solution?
Thanks in advance.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <cstdio>
using namespace std;
int main()
{
   char        taskToDo[120] ={'\0'};
   int         loadingString;
   int         displayString;
   int         taskNum;
   cin   >> taskNum;
   cout  << endl;
      // Loading String;
   for (loadingString = 0; loadingString < taskNum; loadingString++)
   {
      cout  << loadingString + 1 << ": ";
      cin   >> taskToDo;
   }
   cout  << endl;
      //Display String;
   for (displayString = 0; displayString < loadingString; displayString++)
   {
      cout  << displayString + 1 << ": ";
      cout  << taskToDo << endl;
   }
   return 0;
}
I suspect it's because when you use the extraction operators (>>) on cin, it leaves the terminating enter/space/etc at the end of the data, so when you go to read with getline() or anything else, it immediately sees that newline character and ends the input for the first task.

You can use cin.ignore() after reading via the extraction operator to remove the extraneous whitespace, or possibly use getline() for all input and convert from an std::string to an integer when necessary. This will also fix a possible problem where the user enters a letter instead of a number.

You will also be using std::strings instead of C-style character arrays, which is good as the former is much easier to use. I don't know why you are including cstdio anyway.
Hi Zhuge,
Thank you very much indeed. The problem is solved now.
About cstdio; if i use gets ();
Avoid gets(). It uses C-style arrays when you could use the much simpler C++ std::strings, and has the possibility of writing beyond the amount of memory you have allocated for your C-string.
Topic archived. No new replies allowed.