如何从文本文件中读取多个单词

How to read in multiple words from a text file?

本文关键字:读取 单词 文件 文本      更新时间:2023-10-16

我有一个关于 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;
}

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

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

我将如何解决这个问题?

如果你只想在'.'上拆分,那么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(" ntrv");
    size_t last = str.find_last_not_of(" ntrv");
    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)

这个答案告诉你如何做到这一点。为了简单起见,您可能必须使用 std::getline 拆分字符串。

编辑:添加了对文件的检查和有关 C++11 功能的说明。

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

默认情况下,>>提取运算符跳过空格,因此,它只提取一个单词。

要一次读取一行,可以使用 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;
}
#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

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

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

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

使用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;
}