#include <iostream>
#include <fstream>
#include <iomanip> // For formatted input
#include <cctype> // For the "is" character functions
#include <cstring> // For strncpy, strncat and strlen functions
#include <cstdlib> // For exit function
using namespace std;
int main() {
ifstream fin; // Declare and name the input file stream object
ofstream fout; // Declare and name the output file stream object
char in_file[51]; // Filename for the input file
char out_file[56]; // Filename for the output file
char c; // Current character in the file
cout << "Enter the filename of the input file: ";
cin >> setw(51) >> in_file; //setting max length of file name
strncpy(out_file, in_file, 50);
strncat(out_file, ".norm", 50 - strlen(out_file));
fin.open(in_file);
if(fin.fail()) {
cout << "Cannot open " << in_file << " for reading.\n";
exit(1);
}
fout.open(out_file);
if(fout.fail()) {
cout << "Cannot open " << out_file << " for writing.\n";
exit(1);
}
while(fin.get(c))
{
/* commented this out to see if a switch statement would output differently
if (isupper(c))
{
c=tolower(c);
putchar(c);
}
if (c=='/n')
{
fout<< endl << endl;
}
if (c=='/t')
{
for(int i=0; i<9; i++)
fout<<" ";
}
*/
switch (c)
{
case '\t' : // replace 'tab' by '8 chars'
fout << " ";
break;
case '\n' : //replace 1 newline with 2
fout<<"\n"<<"\n";
break;
default: // use default case to proccess all data and
if (isupper (c)) { // test upper/lower-case.
char c2 = tolower (c);
fout << c2;
} else {
fout << c;
}
}
fin >> noskipws >> c; // read the next character
}
fin.close();
fout.close();
cout << in_file << " has been normalized into " << out_file << endl;
return(0);
}
What I'm trying to do is have some input text file, append it with .norm and output it normalized with: 1.All tabs replaced with 8 spaces, 2.All upper case to lower case, 3.Double space the text. I thought my code would accomplish this, but I'm getting really weird outputs.
Here's an example of a text input:
DOE JOHN 56 45 65 72
DOE jane 42 86 58 69
doe tom 89 92 75 86
which then was output to:
dejh 64 57
o ae4 65 9detm8 27 6
I have no idea what's going wrong and would really appreciate any help.
while(fin.get(c))
reads a character at the beginning of every iteration of the while loop. But inside the while loop body, right at the end
fin >> noskipws >> c;
reads another character. This second character will be promptly written over by while(fin.get(c))
and never be inspected.
This is shown by the OP's output: Every second character is transformed and written to the file.
Recommendation to OP: Learn to use your IDE's debugger. This was a trivial error that would have been immediately apparent if OP stepped through a few loop iterations.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.