在 C 中显示字符串向量

新手上路,请多包涵

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

 #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;
}

所以我的新程序有效。它只是将值放在向量的后面并将它们打印出 8 个单词到一行。我知道有更简单的方法,但我只是在学习向量,而且我会一步一步来。谢谢你们的帮助。

原文由 RudolphRedNose 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 379
1 个回答

不过,此代码无需任何修改即可工作。

来源: https ://gist.github.com/lucianmachado/9a26d5745497ffe5d054

 #include <glob.h>
#include <vector>
#include <string>
inline std::vector<std::string> glob(const std::string& pat){
    using namespace std;
    glob_t glob_result;
    glob(pat.c_str(),GLOB_TILDE,NULL,&glob_result);
    vector<string> ret;
    for(unsigned int i=0;i<glob_result.gl_pathc;++i){
        ret.push_back(string(glob_result.gl_pathv[i]));
    }
    globfree(&glob_result);
    return ret;
}

像这样使用它:

 glob("pattern");

“模式”也可以是 string.c_str()。它还返回字符串,因此您也可以在字符串变量中捕获它。

原文由 starter kit 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏