如何使用文本文件获取更多单词

时间:2017-01-20 20:12:48

标签: c++ input text-files

这是我的代码:

#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;
}

当我输出str时,它只是打印&#34; Has&#34;所以只有文件TO_file中的第一个单词达到了str。为什么是这样?另外,我如何修复它以便我可以接收整个文件?

另外,我遇​​到的另一个问题是,如果我想使用for循环遍历字符串中的每个字母或单词,我可以使用:

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

但是如果我想循环浏览文件直到我到达文件中的最后一个单词或字母,我该怎么办呢?我可以使用&#34; test.txt&#34; .length()或者TO_file.length()?还是有另一种方法可以做到这一点吗?

1 个答案:

答案 0 :(得分:0)

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

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

    TO_file >> str;

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

     string s;
     cin >> s;

如果输入&#34; Hello there!&#34;,编译器只会在变量s中存储第一个字(即Hello)。同样在您的函数中,只有行的第一个单词被转移到 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)

不是简单地获取第一个单词,而是可以将整行放在文件中(只需一行,而不是整个文本文件)并输出。从这里开始应该非常简单。祝你好运!