gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 05:39:35 24 4
gpt4 key购买 nike

我对 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;
}

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

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

我该如何解决这个问题?

最佳答案

如果您只想拆分 '.'那么 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 功能的注释。

关于c++ - 如何从文本文件中读取多个单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37449872/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com