[英]reading from text file and changing values c++
#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);
}
我想要做的是有一些输入文本文件,用 .norm 附加它并输出它标准化:1.所有标签替换为 8 个空格,2.所有大写到小写,3.双倍空间文本。 我以为我的代码会完成这个,但我得到了非常奇怪的输出。
下面是一个文本输入的例子:
DOE JOHN 56 45 65 72
DOE jane 42 86 58 69
doe tom 89 92 75 86
然后输出到:
dejh 64 57
o ae4 65 9detm8 27 6
我不知道出了什么问题,非常感谢任何帮助。
while(fin.get(c))
在 while 循环的每次迭代开始时读取一个字符。 但是在while循环体内部,就在最后
fin >> noskipws >> c;
读取另一个字符。 第二个字符将被while(fin.get(c))
迅速覆盖并且永远不会被检查。
这由 OP 的输出显示:每隔一个字符被转换并写入文件。
给 OP 的建议:学习使用 IDE 的调试器。 这是一个微不足道的错误,如果 OP 逐步执行几次循环迭代,它就会立即显现出来。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.