【问题标题】:How to read in multiple words from a text file?如何从文本文件中读取多个单词?
【发布时间】:2016-05-26 00:52:59
【问题描述】:

我对 C++ 中的文件输入有疑问。我希望能够创建一个字符串变量并从文件中读取一个句子。我该怎么做?这是我目前的代码。

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
string word;
ifstream fin;

// Open the file
fin.open("file.txt");

// Read in the sentence from the file
fin >> word;

cout << word << endl;

return 0;
}

问题是,当我尝试从文件中读取一个句子时,它只读取一个单词而不是句子。

因此,如果我在文本文件中有一个句子(假设没有换行符),它只会打印出单个单词。

我该如何解决这个问题?

【问题讨论】:

标签: c++


【解决方案1】:

如果你只想在 '.' 上拆分那么 Jason Caldwell 的答案就是您想要的:

#include <vector>
#include <string>
#include <fstream>
#include <iostream>

static std::string trim(const std::string& str)
{
    size_t first = str.find_first_not_of(" \n\t\r\v");
    size_t last = str.find_last_not_of(" \n\t\r\v");
    return str.substr(first, (last-first+1));
}

int main()
{
    std::vector<std::string>    sentences;

    std::ifstream ifs("sentences.txt");
    if (ifs.is_open() == false)
    { std::cerr << "Couldn't open file..." << std::endl; return -1; }

    std::string line;
    while(getline(ifs,line, '.'))
    { sentences.emplace_back(trim(line) + "."); }

    for (auto sentence : sentences)
    { std::cout << "sentence: " << sentence << std::endl; }
    ifs.close();
}

请注意,此代码使用 c++11 功能(auto、emplace_back...)

但是,如果您假设一个句子有点复杂,我会再次建议 Jason 使用正则表达式。但请确保您的编译器正确实现它们(例如:g++-4.9)

这个answer 告诉你如何去做。为简单起见,您可能必须使用 std::getline 拆分字符串。

编辑:添加了对文件的检查和关于 c++11 功能的注释。

【讨论】:

    【解决方案2】:

    问题是,当我尝试从文件中读取一个句子时,它只读取一个单词而不是句子。

    &gt;&gt; 提取运算符默认跳过空格,因此它只提取一个单词。

    要一次读取一行,您可以使用std::getline。以下代码将读取文本文件中的第一行。您可以将getline 放入while 循环中以逐行读取。

    int main()
    {
        string line;
        ifstream fin("file.txt");
    
        // Read in the sentence from the file
        getline(fin, line);
        cout << line << '\n';
    
        return 0;
    }
    

    【讨论】:

      【解决方案3】:
      #include <iostream>
      #include <fstream>
      #include <string>
      #include <vector>
      using namespace std;
      
      int main()
      {
          string word; // You have to give word an actual string for this to work xd
          ofstream writer("file.txt");//Creating the text document // Creating the variable that writes to it
          ifstream fin("file.txt");//The variable that reads it`
      
          if(!writer){//Checking to make sure it nothing bad occurred when opening file
              cout << "An error occurred opening " << writer;
              return 1; //Return an error occurred
          }else{
              cout << word; // Print the string word whatever it is on file.txt
          }
      
          char letter;//To get every letter that get iterated over
          vector <string> textInFile(999999);//Saves letter into an array
      
          if(!fin){
              cout<<"Problem opening"<<fin; // Check if file opened safely
          }else{
              for(int x = 0; ! fin.eof(); x++){//eof = End of file // It basically iterates over the entire .txt;
                  fin.get(letter); // Gets every letter
                  textInFile[x] = letter; // vector stores the letters
              }
      
              for(int x = 0; x < textInFile.size(); x++){ // For size of <vector> textInFile iterate over all indexes
                  cout << textInFile[x]; // Prints every letter in the vector
              }
          }
          cout<<endl;
          fin.close();
      
          return 0;
      }
      

      抱歉这篇凌乱的帖子,这就像我的第一篇帖子,我不知道这个拳击东西是如何运作的 xd

      【讨论】:

        【解决方案4】:

        getline 是您要查找的内容: http://www.cplusplus.com/reference/string/string/getline/

        对于更复杂的模式匹配,正则表达式可能有用: http://www.cplusplus.com/reference/regex/

        这里发布了一个类似的问题,有很多回复: http://www.cplusplus.com/forum/general/94419/

        【讨论】:

          【解决方案5】:

          使用getline

          #include <iostream>
          #include <fstream>
          #include <string>
          #include <set>
          #include <algorithm>
          #include <cctype>
          
          using namespace std;
          
          int main()
          {
             string sentence;
             set <string> sentences;
          
            ifstream file("thisfile.txt");
          
            if(file.is_open())
            {
              while(getline(file, sentence, "."))
              {
                sentence.erase(remove_if(sentence.begin(), sentence.end(), IsChars("\n")), sentence.end());
                sentences.insert(sentence);
              }
            }
          
            file.close(); //close file
          
            return 0;
          } 
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-11-08
            • 2016-02-12
            • 1970-01-01
            • 2015-06-09
            • 2011-04-12
            相关资源
            最近更新 更多