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

时间:2016-05-26 00:52:59

标签: c++

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

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

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

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

我该如何解决这个问题?

5 个答案:

答案 0 :(得分:1)

如果你只想分开'。'然后贾森考德威尔回答你正在寻找的东西:

#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功能的注释。

答案 1 :(得分:0)

getline是您正在寻找的内容: http://www.cplusplus.com/reference/string/string/getline/

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

此处发布了一个类似的问题,其中包含大量回复: http://www.cplusplus.com/forum/general/94419/

答案 2 :(得分: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

答案 3 :(得分:0)

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

答案 4 :(得分:0)

  

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

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

要一次阅读一行,您可以使用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;
}
相关问题