Aug 27, 2013 at 11:01am UTC
Hi everyone,
this is part of my code,
for(i=0; i<number; i++){
cout << "Enter the No."<<i+1<< " input filename:" << endl;
cin.getline(name[i],50);
}
why the output I get is (when number == 2)
"
Enter the NO.1 File name:
Enter the NO.2 File name:
"
without any space let me put in my file name?
ps: the variable name is a two dimensional array "char name[i][j]", which I use to store the file name, which is a string. Is there any better idea I can solve this problem?
Thanks!
Last edited on Aug 27, 2013 at 11:07am UTC
Aug 27, 2013 at 11:31am UTC
I think that the problem is that there is new line character in the input buffer. Begore using function getline you should clear the input buffer.
Aug 27, 2013 at 11:33am UTC
Instead of a two-dimensional char array, use a 1D std::string array.
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 <string>
using namespace std;
#define MAX_FILES 50
int main() {
string name[MAX_FILES];
int numOfFiles;
cout << "Enter the number of files: " ;
cin >> numOfFiles;
cin.ignore();
for ( int i = 0; i < numOfFiles; i++ ) {
cout << "Enter the No." << i + 1 << " input filename: " << endl;
getline( cin, name[i] );
}
return 0;
}
EDIT: As vlad suggested, cin.ignore() added.
Last edited on Aug 27, 2013 at 12:06pm UTC