c++ - 在 C++ 中显示字符串 vector

标签 c++ vector push-back

如果这是一个重复的问题,我很抱歉,但我已经尝试寻找答案但空手而归。所以基本上我只想将字符串(单个单词)添加到 vector 的后面,然后将存储的字符串显示为单个字符串。我是菜鸟。

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


int main(int a, char* b [])
{
    vector<string> userString;      
    string word;        
    string sentence = "";           
    for (decltype(userString.size()) i = 0; i <= userString.size() - 1; i++)
    {
        cin >> word;
        userString.push_back(word);
        sentence += userString[i] + " ";
    }
    cout << sentence;
    system("PAUSE");
    return 0;
}

为什么这行不通?

编辑

int main(int a, char* b [])
{
    cout << "Enter a sequence of words. Enter '.' \n";
    vector<string> userString;      
    string word;                    
    string sentence = "";           /
    int wordCount = 0;
    while (getline(cin, word))
    {
        if (word == ".")
        {
            break;
        }
        userString.push_back(word);
    }
    for (decltype(userString.size()) i = 0; i <= userString.size() - 1; i++)
    {
        sentence += userString[i] + " ";
        wordCount += 1;
        if (wordCount == 8)
        {
            sentence = sentence + "\n";
                    wordCount = 0;
        }
    }
    cout << sentence << endl; 
    system("PAUSE");
    return 0;
}

所以我的新程序可以运行了。它只是将值放在 vector 的后面,并将它们打印出 8 个单词到一行。我知道有更简单的方法,但我只是在学习 vector ,而且我正在逐步进行。感谢大家的帮助。

最佳答案

因为 userString 是空的。你只声明它

vector<string> userString;     

但永远不要添加任何东西,所以 for 循环甚至不会运行。

关于c++ - 在 C++ 中显示字符串 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17938166/

相关文章:

c++ - 我的基于可变参数模板的包装函数有什么问题?

c++ - std::vector 类与非成员函数(连同 typedef)

c++ - 当我将字符串转换为 vector<byte> 时出现字符串迭代器不兼容错误

r - 在向量 R 中的值分隔符处拆分元素

C++ vector push_back 方法和临时对象创建

c++ - 在 C++ 中对 STL 列表使用 push_back() 会导致访问冲突、崩溃

c++ - 嵌套的 hashmap 初始化列表

c++ - 检查函数是否单调

C++ 忽略空的第一行

c++ - 尝试将元组推回 const vector 时出错