c++ 中的文件 i/o
我想做的就是打印 readme.txt 的内容 20 次..请帮忙。
int main()
{
ifstream myfile;
string line;
int i;
myfile.open ("readme.txt");
if (myfile.is_open()){
while (i<20){
i++;
if(!myfile.eof()){
cout << "asdasd" << "\t";
myfile.seekg(0, ios::beg);
}
getline (myfile,line);
cout << line << endl;
}
cout << endl;
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
all i want to do is print the contents of readme.txt 20 times.. please help.
int main()
{
ifstream myfile;
string line;
int i;
myfile.open ("readme.txt");
if (myfile.is_open()){
while (i<20){
i++;
if(!myfile.eof()){
cout << "asdasd" << "\t";
myfile.seekg(0, ios::beg);
}
getline (myfile,line);
cout << line << endl;
}
cout << endl;
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
这可以完成工作:
This does the jobs man :
您的代码有几个问题。首先我没有初始化。第二次读取文件内容应该在循环之前而不是之后完成一次,您应该打印 asdasd 打印的文件内容,以查看文件内容打印的次数与循环运行的次数一样多。
there are several problems with your code. first i isn't initialized. Second reading the contents of the file should be done once before the loop not after, you should print the contents of the file where asdasd is printed to see the contents of the file printed as many times as the loop runs.
您应该这样做(伪代码):
编辑:事实上,您真正的问题是未初始化的变量
i
。更深层次的原因是你使用了while
,其中for
更合适You should do this (pseudocode):
Edit: In fact your real problem is the uninitialized variable
i
. The deeper reason was that you usedwhile
wherefor
was more appropriate根据您的代码,如果您不在文件末尾,则您将打印
asdasd
。According to your code, you are printing
asdasd
if you are NOT at the end of the file.您已完成
,但此
i
尚未初始化。You have
and this
i
is not initialized.您可能想丢失
!
。您将在每次循环中倒回至文件的开头。(基里尔在这里也有一点......)
You might want to lose the
!
. You are rewinding to the beginning of the file on each loop.(Kiril also has a point here...)
不确定这是否能解决您的问题,但您的结构非常糟糕。当你不知道要循环多少次时使用 while,否则使用 for 循环。像下面这样的东西应该没问题
希望这会有所帮助。
Not sure if this will fix your problem but your structure is pretty bad. Use a while when you don't know how many times you want to loop, otherwise use a for loop. Something like below should be ok
Hope this helps.
我不知道你为什么要这样做,但这段代码有效:
如果文件在迭代过程中没有改变,那就更好了
I don't know why you wanna do that but this code works:
If the file is not changing during the iteration, this is even better