在 C++ 中显示字符串向量 [英] Displaying a vector of strings in C++

查看:30
本文介绍了在 C++ 中显示字符串向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm sorry if this is a repeat question but I already tried to search for an answer and came up empty handed. So basically I just want to add strings (single words) to the back of a vector and then display the stored strings as a single string. I am quite the rookie.

#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 个字.我知道有更简单的方法,但我只是在学习向量,而且我正在逐步进行.感谢大家的帮助.

So my new program works. It just puts values at the back of a vector and prints them out 8 words to a line. I know there's easier ways but I'm just learning vectors and I'm going in baby steps. Thanks for the help guys.

推荐答案

因为 userString 为空.你只声明它

Because userString is empty. You only declare it

vector<string> userString;     

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

but never add anything, so the for loop won't even run.

这篇关于在 C++ 中显示字符串向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆