【发布时间】:2016-02-28 23:09:54
【问题描述】:
我编写了一个代码,它通过在行尾添加“-”字符来读取文本文件并打印到标准输出。我测试了两个不同的名称文件,它们具有相同的文本但结果不同。我不明白。请有人解释一下。
我的代码:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(int argc, char* argv[])
{
ifstream file (argv[1]);
string line;
if (file.is_open())
{
while ( getline (file,line) )
{
cout << line.c_str() << '-' << endl;
}
file.close();
}
return 0;
}
我用它运行这个命令:
./a.out test.txt
输出是:
Some text written-
More input to this file-
Data01323526-
AnotherData09142-
然后我用它运行这个命令:
./a.out pr.txt
最后一条命令的输出是:
-ome text written
-ore input to this file
-ata01323526
AnotherData09142-
“pr.txt”和“test.txt”有相同的文本。您可以在那里下载它们进行测试: http://www.megafileupload.com/anP3/pr.txt
http://www.megafileupload.com/anP4/test.txt
它们有相同的文本,有 71 个字符。
Some text written
More input to this file
Data01323526
AnotherData09142
为什么输出不同?我怎样才能读到输出总是一样的?
【问题讨论】:
-
是OT,但你为什么用
line.c_str而不是line? -
我一般用这种方式,会不会改变输出?