c++ - 如何将 cin 读入 vector

标签 c++ vector cin

我需要允许用户在控制台或文件中输入一个写作示例,然后让我的程序将该输入拆分为一个词 vector (每个 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);
        }
    }
}

最佳答案

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

关于c++ - 如何将 cin 读入 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53473645/

相关文章:

c++ - 在 C++ 中更新 vector 或列表的多个调用异步

c++ - Cuda(warpSize 为负数)

c++ - 如何填充包含指针数组的结构体数组

c++ - 从文件 C++ 中保存和读取双 vector

r - 生成一个序列,该序列是 R 中另一个向量的递增部分

c++ - 删除二维 vector 的元素

C++ 如何检查 std::cin 缓冲区是否为空

c++ - cout 打印不正确的值

c++ - cout 和 cin 在 C++ 的函数中重复?

c++ - 是否可以使用带有 CMake 的 C++ 在 Linux 上创建 Windows exe?