如何将 cin 读入向量

How to read cin into a vector

我需要允许用户在控制台或文件中输入一个写作示例,然后让我的程序将该输入拆分为一个词向量(每个向量项一个词)。这是我当前的代码:

while(cin >> inputString) {
    wordVector.push_back(inputString);
}

问题是,当我 运行 这样做时,它可以正常工作,直到到达用户输入的末尾。然后它似乎只是无休止地循环。

inputString 是字符串类型。

wordVector 是字符串类型。

这是完整代码:(损坏的代码在底部)

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

// Debug message flag
const bool DEBUG = false;

// Prototypes
void splitToVectors(vector<string>&,vector<string>&,vector<int>&,int &);
double avSentLength(const vector<string>);
double avWordSyl(const vector<string>,const vector<char>);
double percentSentLong(const vector<int>,int);
int numSyllables(const vector<char>);
void nextScreen(int);

int main() {

    // Initialize variables and vectors
    bool validate;
    int characters,words,sentences = 0,syllables;
    string file;
    string inputString;
    char inputChar;
    int input;

    vector<string> wordVector;
    vector<char> charVector;
    vector<string> sentenceVector;
    vector<int> numWordsInSent;

    // Get writing sample
    do {

        // Request preferred location
        validate = true;
        cout << "Would you like to:" << endl;
        cout << "  1. Enter the writing sample in the console" << endl;
        cout << "  2. Read from a file" << endl << " > ";

        // Validate
        if(!(cin >> input)) { // This error checking condition functions as the cin
            validate = false;
            cin.clear();
            cin.ignore(100, '\n');
        }
        if((input < 1) || (input > 2)) {
            validate = false;
    }

    } while(!validate);


    // Transfer selected source to wordVector
    if(input == 1) {

        // Request sample
        cout << "Please enter the writing sample below:" << endl << endl;

        // Input sample
        while(cin >> inputString) {
            wordVector.push_back(inputString);
        }
    }
}

您确定您正在点击 Ctrl-D 以正确发送 EOF 吗?以下代码似乎有效:

int main()
{
    vector<string> words;
    std::string inputString;
    while (cin >> inputString)
    {
        words.push_back(inputString);
    }

    vector<string>::iterator it;
    for (it = words.begin(); it != words.end(); it++)
    {
        cout << *it << "\n";
    }

    return 0;
}

在交互中 console/compiler while(cin >> inputString) 将继续等待用户输入。

可以在从静态标准输入读取数据的非交互式console/compiler上工作。但值得注意的是,在(最符合标准的)交互式编译器中,cin >> inputString 将继续等待用户输入,并且将(应该)not 评估为 false 直到发生错误在阅读输入中。

您可能希望向程序发出输入已完成的信号。这样做的一种方法是提供一个关键字,例如 EOF,这将打破 while 循环(尽管这样做的缺点是您不能在输入的内容中使用 EOF)。

我还没有了解迭代器。所以我想出了以下解决方案: 我使用 getline 获取所有输入并将其放入字符串变量中。然后我有一个 for 循环 运行 通过它,构建一个临时字符串,直到它遇到 space。当它看到 space 时,它会将临​​时变量添加到向量中,并重置临时变量。它以这种方式继续,直到到达字符串的末尾。