|
|
|
| Statement | | Skips Leading Whitespace? |
| | | cin >> inputStr; | | At the first trailing whitespace character (which is not consumed) | | cin.get(inputStr, 21); | | When either 20 characters are read or '\n' is encountered (which is not consumed) |
|
|
|
|
|
|
Run-Time Input of File Names |
|
|
|
|
|
|
|
|
Until now, our programs that have read from input files and written to output files have included code similar to this: |
|
|
|
|
|
|
|
|
ifstream inFile; // Input file to be analyzed
inFile.open("datafile.dat");
if ( !inFile )
{
cout << "** Can't open input file **" << endl;
return 1;
}
.
.
. |
|
|
|
|
|
|
|
|
The open function associated with the ifstream data type requires a string parameter that specifies the name of the actual data file on disk. By using a string constant, as in the above example, the file name is fixed at compile time. That is, the program works only for this one particular disk file. |
|
|
|
|
|
|
|
|
We often want to make a program more flexible by allowing the file name to be determined at run time. A common technique is to prompt the user for the name of the file, read the user's response into a string variable, and pass the string variable as a parameter to the open function. The following code fragment, which is another example of the use of the get and ignore functions, demonstrates the run-time input of a file name. |
|
|
|
|
|
|
|
|
ifstream inFile; // Input file to be analyzed
char fileName[51]; // Max. 50 characters plus '\0'
cout << "Enter the input file name: ";
cin.get(fileName, 51); // Read at most 50 characters
cin.ignore(100, '\n'); // Skip rest of input line
inFile.open(fileName);
if ( !inFile )
{ |
|
|
|
|
|