简体   繁体   English

在 C++ 中显示字符串向量

[英]Displaying a vector of strings in 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;
}

Why doesn't this work?为什么这不起作用?

EDIT编辑

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

So my new program works.所以我的新程序有效。 It just puts values at the back of a vector and prints them out 8 words to a line.它只是将值放在向量的后面,并将它们打印成一行 8 个字。 I know there's easier ways but I'm just learning vectors and I'm going in baby steps.我知道有更简单的方法,但我只是在学习向量,而且我正在逐步进行。 Thanks for the help guys.谢谢你们的帮助。

Because userString is empty. 因为userString为空。 You only declare it 你只声明它

vector<string> userString;     

but never add anything, so the for loop won't even run. 但从不添加任何东西,因此for循环甚至不会运行。

Your vector<string> userString has size 0 , so the loop is never entered. vector<string> userString大小为0 ,因此永远不会输入循环。 You could start with a vector of a given size: 您可以从给定大小的向量开始:

vector<string> userString(10);      
string word;        
string sentence;           
for (decltype(userString.size()) i = 0; i < userString.size(); ++i)
{
    cin >> word;
    userString[i] = word;
    sentence += userString[i] + " ";
}

although it is not clear why you need the vector at all: 虽然不清楚为什么你需要矢量:

string word;        
string sentence;           
for (int i = 0; i < 10; ++i)
{
    cin >> word;
    sentence += word + " ";
}

If you don't want to have a fixed limit on the number of input words, you can use std::getline in a while loop, checking against a certain input, eg "q" : 如果你不想对输入字的数量有一个固定的限制,你可以在while循环中使用std::getline ,检查某个输入,例如"q"

while (std::getline(std::cin, word) && word != "q")
{
    sentence += word + " ";
}

This will add words to sentence until you type "q". 这将在sentence添加单词,直到您键入“q”。

You have to insert the elements using the insert method present in vectors STL, check the below program to add the elements to it, and you can use in the same way in your program. 您必须使用向量STL中的插入方法插入元素,检查以下程序以向其添加元素,并且可以在程序中以相同的方式使用。

#include <iostream>
#include <vector>
#include <string.h>

int main ()
{
  std::vector<std::string> myvector ;
  std::vector<std::string>::iterator it;

   it = myvector.begin();
  std::string myarray [] = { "Hi","hello","wassup" };
  myvector.insert (myvector.begin(), myarray, myarray+3);

  std::cout << "myvector contains:";
  for (it=myvector.begin(); it<myvector.end(); it++)
    std::cout << ' ' << *it;
    std::cout << '\n';

  return 0;
}

You ask two questions; 你问两个问题; your title says "Displaying a vector of strings", but you're not actually doing that, you actually build a single string composed of all the strings and output that. 你的标题是“显示一个字符串向量”,但你实际上并没有这样做,你实际上构建了一个由所有字符串组成的字符串并输出它。

Your question body asks "Why doesn't this work". 你的问题机构问“为什么这不起作用”。

It doesn't work because your for loop is constrained by "userString.size()" which is 0, and you test your loop variable for being "userString.size() - 1". 它不起作用,因为你的for循环受“userString.size()”约束,并且你测试你的循环变量是“userString.size() - 1”。 The condition of a for() loop is tested before permitting execution of the first iteration. 在允许执行第一次迭代之前测试for()循环的条件。

int n = 1;
for (int i = 1; i < n; ++i) {
    std::cout << i << endl;
}

will print exactly nothing. 什么都不打印。

So your loop executes exactly no iterations, leaving userString and sentence empty. 因此,您的循环执行完全没有迭代,将userString和句子留空。

Lastly, your code has absolutely zero reason to use a vector. 最后,您的代码绝对没有理由使用向量。 The fact that you used "decltype(userString.size())" instead of "size_t" or "auto", while claiming to be a rookie, suggests you're either reading a book from back to front or you are setting yourself up to fail a class. 您使用“decltype(userString.size())”代替“size_t”或“auto”这一事实虽然声称自己是新手,但这表明您要么从后到前阅读一本书,要么就是在为自己辩护失败了。

So to answer your question at the end of your post: It doesn't work because you didn't step through it with a debugger and inspect the values as it went. 所以在帖子的最后回答你的问题:它不起作用,因为你没有使用调试器逐步执行它并检查值。 While I say it tongue-in-cheek, I'm going to leave it out there. 虽然我说出来,但我会把它留在那里。

vector.size() returns the size of a vector. vector.size()返回向量的大小。 You didn't put any string in the vector before the loop , so the size of the vector is 0. It will never enter the loop. 你没有在循环之前在向量中放置任何字符串,因此向量的大小为0.它永远不会进入循环。 First put some data in the vector and then try to add them. 首先在矢量中放入一些数据,然后尝试添加它们。 You can take input from the user for the number of string user wants to enter. 您可以从用户那里获取输入的字符串数量。

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


int main(int a, char* b [])
{
    vector<string> userString;
    string word;
    string sentence = "";
    int SIZE;
    cin>>SIZE;    //what will be the size of the vector
    for (int i = 0; i < SIZE; i++)
    {
        cin >> word;
        userString.push_back(word);
        sentence += userString[i] + " ";
    }
    cout << sentence;
    system("PAUSE");
    return 0;
}

another thing, actually you don't have to use a vector to do this.Two strings can do the job for you. 另外一件事,实际上你不必使用向量来做这个。两个字符串可以为你完成这项工作。

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


int main(int a, char* b [])
{
   // vector<string> userString;
    string word;
    string sentence = "";
    int SIZE;
    cin>>SIZE;    //what will be the size of the vector
    for (int i = 0; i < SIZE; i++)
    {
        cin >> word;
        sentence += word+ " ";
    }
    cout << sentence;
    system("PAUSE");
    return 0;
}

and if you want to enter string until the user wish , code will be like this: 如果你想输入字符串直到用户希望,代码将是这样的:

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


int main(int a, char* b [])
{
   // vector<string> userString;
    string word;
    string sentence = "";
    //int SIZE;
    //cin>>SIZE;    //what will be the size of the vector
    while(cin>>word)
    {
        //cin >> word;
        sentence += word+ " ";
    }
    cout << sentence;
  //  system("PAUSE");
    return 0;
}

This code works without any modifications though.但是,此代码无需任何修改即可工作。

Source: https://gist.github.com/lucianmachado/9a26d5745497ffe5d054来源: 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;
}

Use it like:像这样使用它:

glob("pattern");

"pattern" could also be a string.c_str(). “模式”也可以是 string.c_str()。 It also returns the strings so you can catch it too in a string variable for instance.它还返回字符串,因此您也可以在字符串变量中捕获它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM