如何从C 向量访问单个单词

How to access individual word from c++ vector?

本文关键字:访问 单个单 向量      更新时间:2023-10-16

在程序的末尾,我输出了向量的内容,从文本文件输入字符串。输出了整个向量,但是如何仅输出一个单词?我之所以问这个,是因为以后我需要修改每个字符串。

#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 favourites",它将很好地分为单词。如果线路上也有标点符号,则words中的某些字符串将嵌入标点符号,例如"world."。如果您关心的话,可以学习使用std::string成员函数来搜索和编辑字符串。

在标点符号的情况下,您可以使用 std::erase(std::remove_if(word.begin(), word.end(), std::ispunct), word.end())删除它(更多详细信息/说明(。

phrase[i] == phrase[i]
好吧,那只是多余的。对于持有字符串的矢量,这将始终返回。

for(int i = 0; (...); i++){
   while( (...) ){
       i++;
   }
}

您正在修改变量i两次,其中单个for loop。一次进入for的第三个参数,一次进入内部while loop。几乎是从来都不是一个好主意

这里发生的事情是您设置i=0,然后立即将其设置为向量的最后一个元素(因为while中的第二个条件始终是正确的(。

然后,您将此元素打印到控制台,这是文本文件的最后一个 line

您想做的是:
1.逐条加载文本文件进入向量。
2.向量的每个元素都会容纳一条线。
3.将每行分为单词的向量(空间分开(。
4.与最终的向量一起工作。

或网上:
1.开始时通过单词加载文件。

vector<string> words; 
copy( istream_iterator<string>{YourFileStream}, istream_iterator<string>{}, back_inserter{words} ); // this will copy the content of file directly into vector, white-space-separated (no need for while loop to do it)
for ( auto i = phrase.begin(); i != phrase.end(); ++i ) // it's the proper c++ way of iterating over a vector. very similar, but variable i will point to every element of vector in order ( not just to the index of an element )
{
      // do some work on *i. at least: 
      std::cout << *i; // dereference operator (*) is needed here, since i doesn't hold index of an element, it's a "pointer" to an element
}

如果您需要第一种方法(以不同行中的单词区分(,则可以在这里找到一些出色的方法来通过任何分配计(例如,空间(分开字符串:最优雅的方法来迭代一个单词字符串