2017-01-20 30 views
1

这里是我的代码:如何采取比只用一个词多个文本文件

#include <iostream> 
#include <fstream> 
using namespace std; 

int main() 
{ 
    //ifstream for input from files to program 
    //ofstream for output to file 
    string str; 

    ofstream PI_file("test.txt"); 
    PI_file <<"Has this reached the file"; 
    PI_file.close(); 

    ifstream TO_file("test.txt"); 
    TO_file >> str; 

    cout << str; 
} 

当我输出海峡,它只是打印“有”,所以只能从文件TO_file第一个字已经达到海峡。为什么是这样?另外,我该如何解决这个问题,以便我可以接收整个文件?

此外,另一个问题我是,如果我想通过一个字符串中的每个字母或文字使用一个for循环回路,我可以使用:

for (int i=0; i<string.length(); i++) 

但是,如果我通过一个想循环文件,直到我到达文件中的最后一个字或字母,我怎么能做到这一点?我可以使用“test.txt”.length()或者TO_file.length()吗?还是有另一种方法来做到这一点?

+1

您是否尝试过缩进代码以使其可读性为 –

+2

这是[流输入](http://en.cppreference.com/w/cpp/string/basic_string/operator_ltltgtgt)的工作原理。如果您想要整行,请改用['std :: getline'](http://en.cppreference.com/w/cpp/string/basic_string/getline)。 –

+1

对于更大的数量,有'std :: istream :: read',您可以在其中指定要读取的数量。 –

回答

0

只是想纠正你,你发送到test.txt的整个行已经成功地到达了那里。我只是测试你的代码。虽然它只输出已有,整行已经到达文件实际上是在test.txt中。

代码中的问题是您如何阅读文本文件。当您执行以下行时,

TO_file >> str; 

您忘记了str是字符串类型的变量。如果您尝试接受字符串变量的输入,编译器将只接受空格字符之前存在的内容,就像您的行中有一个字在之后。例如,

 string s; 
    cin >> s; 

如果你输入“你好!”,在变量s编译器将只存储第一个字(即你好)。同样在你的函数中,只有你的行的第一个字被传送到变量str变量。

您将不得不重写您的代码以阅读test.txt。我将提供一个示例模板从cplusplus.com如下:

 string line; // You store the string sentence in this variable 
     ifstream myfile ("example.txt"); // You open the file in read mode 
     if (myfile.is_open()) // If the file is successfully accessed and opened, then: 
     { 
     while (getline (myfile,line)) // Get every line from the file until you reach end of file 
     { 
      cout << line << '\n'; // Here you do whatever you want to do with the line from the file 
     } 
     myfile.close(); // Close the file at the end 
     } 

     else cout << "Unable to open file"; // If the file cannot open, print error message 

你的代码的错误是固定在while循环的条件:

 getline (myfile,line) 

而不是简单的得到的第一个字,你可以将整行放在一个文件中(只有一行,而不是整个文本文件)并输出。从这里开始应该很简单。祝你好运!

+0

为什么你把getline作为getline()的长度() –

+0

噢,好的谢谢,但是通过把getline(myfile,line)放在while循环条件中,how是否它实际上获得了该行,尽管它是while循环的一个条件 –

+0

我明白为什么您已将length取为getline中的长度,但现在程序现在如何在读取整个文件后停止从文件读取行文件?此外,整个文件不会是一个getline,因为(我认为)getline需要输入,直到输入字符被按下,因为这是一个文件,输入不会被按下。 –

相关问题