Re: [Dev-C++] OK, here's another stupid question....................
Open Source C & C++ IDE for Windows
Brought to you by:
claplace
|
From: <or...@vp...> - 2003-01-28 08:05:23
|
Hello!
Dany P. Wu wrote:
> They always say "There are no such thing as stupid questions, just
> plenty of inquisitive idiots" but here it goes........
Haha. Your question was actually a very good one. It took me at least 20
mins to figure out, but I have found what is the problem.
When you use cin before you use getline, it leaves a newline character
in the input (the console) and when getline is called it reads that
newline character and returns with an empty line. To fix this, use the
ignore function after you use cin and before you call getline:
cin.ignore(10,'\n'); // skip 10 chars until reaches '\n'
This will ignore all the '\n' characters so that getline will work properly.
Here is where to put it exactly:
> ============================================
> #include <iostream>
> #include <string>
>
> #define TAB '\t'
>
> main()
> {
> using namespace std;
>
> //Define how many planets there are
> int MAX;
> cout << "Enter the number of planets: ";
> cin >> MAX;
> //Define max length of planet names
> int LENGTH;
> cout << "Enter max length of planet names: ";
> cin >> LENGTH;
> cout <<"There will be " << MAX << " planets" <<endl;
> cout << "Each will be " << LENGTH << " chars long" <<endl;
> LENGTH = LENGTH + 1;
>
> //Define the 2 arrays, planet names and distances
> char name[LENGTH];
> char planet[MAX][LENGTH];
> int distance[MAX];
> int DIST;
> int index = 0;
cin.ignore(10,'\n'); // skip 10 chars until reaches '\n'
>
> while (index < MAX)
> {
> cout << index << endl; //I put this in here to show that it
> skipped the value 0
> cin.getline(name,LENGTH);
> strcpy(planet[index],name);
> index++;
> }
>
> index = 0;
>
> for (index = 0; index < MAX; index++)
> {
> cout << endl << planet[index] << endl;
> }
>
> system("PAUSE");
> return(0);
> }
> ============================================
--
Greetings,
Balázs
|