gpt4 book ai didi

c++ - 如何从 C++ vector 中访问单个单词?

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:06:06 29 4
gpt4 key购买 nike

在程序结束时,我输出了一个 vector 的内容,字符串是从文本文件中输入的。整个vector都输出了,怎么只输出一个词呢?我问这个是因为我稍后需要修改每个字符串。

#include<iostream>
#include<fstream>
#include<vector>
#include<algorithm>
using namespace std;



int main(){

ifstream in;
string line, file_name;
vector <string> phrase;
int total_words, total_letters, total_chars;

cout << "PIG LATIN PROGRAM" << endl;

cout << "Which file are you accessing? : ";
cin >> file_name;

in.open(file_name);

if (in.fail()) cout << "\nFile not found!" << endl;


while(getline(in, line)) phrase.push_back(line);



for(int i = 0; i < phrase.size(); i++){

int limit = phrase.size() - 1;
while(i < limit && phrase[i] == phrase[i]){
i++;

}
cout << phrase[i];


}

最佳答案

您可以首先在 phrase[i] 中的空格处拆分行:

std::istringstream iss{phrase[i]};
std::vector<std::string> words;
std::string word;
while (iss >> word)
words.push_back(std::move(word));

std::istringstream创建一个输入流 - 有点像 cin - 包含从文件中读取并存储在 phrase[i] 中的整行文本。如果您随后使用 >> word,它将一次提取一个以空格分隔的文本单词。

假设您的台词/phrase[i] 输入包含“the blue socks were her favorites”,它将很好地拆分成单词。如果该行中还有标点符号,words 中的某些字符串将嵌入该标点符号,例如“世界。”。如果你关心这个,你可以学习使用 std::string搜索和编辑字符串的成员函数。

在标点符号的情况下,你可以使用std::erase(std::remove_if(word.begin(), word.end(), std::ispunct), word.end()) 删除它(进一步 details/explanation ) .

关于c++ - 如何从 C++ vector 中访问单个单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50082213/

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