【发布时间】:2017-04-25 22:59:58
【问题描述】:
这是我的代码:
//main.cpp
#include <iostream>
#include <fstream> //files
#include <string> //strings
#include <sstream> //stringstreams
string intToString(int wert){
ostringstream strout;
string str;
strout<<wert;
str=strout.str();
return str;}
int stringToInt(string str){
istringstream strin;
unsigned long long intVar;
strin.str(str);
strin>>intVar;
return intVar;}
string wordsToAscii(string wort){
string hold;
for(int j=0;j<wort.length();j+=3){
for(int i=j;i<j+3;i++){
if(int(wort[i]>=100))
hold=hold+intToString(int(wort[i]));
if(int(wort[i]>=10 && wort[i]<=99))
hold=hold+"0"+intToString(int(wort[i]));
if(int(wort[i]<=9))
hold=hold+"00"+intToString(int(wort[i]));
}
}
return hold;
}
string AsciiToWords(string wort){
string hold;
string total;
for(int j=0;j<wort.length();j+=15)
for(int i=j;i<j+15;i+=3){
hold="\0";
for(int k=i;k<i+3;k++)
hold+=wort[k];
if(hold=="000")
break;
total+=stringToInt(hold);
}
return total;
}
int main(){
string str;
ifstream f ("input");
ofstream g ("temp");
while(!f.eof())
if(getline(f,str)){
cout<<wordsToAscii(str)<<"\n";
g<<wordsToAscii(str)<<"\n";}
f.close();
g.close();
ifstream h ("temp");
ofstream i ("output");
while(!h.eof())
if(getline(h,str)){
cout<<AsciiToWords(str)<<"\n";
i<<AsciiToWords(str)<<"\n";}
h.close();
i.close();
return 0;
}
输入:(文件)
first line test1
second line test2
last line test3
testA testB testC
one
two
临时:(文件)
102105114115116032108105110101032116101115116049000000
115101099111110100032108105110101032116101115116050000
108097115116032108105110101032116101115116051
116101115116065032116101115116066032116101115116067000
111110101
116119111
输出:(文件)
first line test1
second line test2
last line test3
testA testB testC
one
输出:(在终端中)
102105114115116032108105110101032116101115116049000000
115101099111110100032108105110101032116101115116050000
108097115116032108105110101032116101115116051
116101115116065032116101115116066032116101115116067000
111110101
116119111
first line test1
second line test2
last line test3
testA testB testC
oneA
twoA
第一个函数将字符转换为其对应的 ASCII 数字。 第二个应该把它转换回来。
这两个功能似乎运作良好。问题是文件和终端中的输出不同。唯一的区别是cout<< 而不是i<<
此外,在输入不同的情况下,有时最后一行会被写入两次,或者根本不写入。我自己无法解释。我研究了几个小时,改变了读取/写入文件的方式,重写了部分代码等,但没有找到原因
提前感谢您的帮助
【问题讨论】:
-
小心你的麦芽汁[i]。在您的代码中,“i”可以大于麦汁长度。
-
stringToInt和intToString是什么? -
即使代码有问题...如何解释不同的输出?
标签: c++ file input output cout