提问者:小点点

如何在一个空数组中添加用户给出字符串并在C++中找到它的长度


我是C++的新手,曾多次尝试从用户那里获取字符串并将其添加到空数组中。 我读了我的书,但没有得到适当的解释。 我明白我的代码是不对的,但我想做的是,要求用户给出一个字符串,直到用户键入“quit”,程序应该接受这些字符串并将其添加到名为listt的空数组中。 之后,我声明了名为len的变量,并试图获得刚才创建的数组的长度。 然而,我得到了几个错误,并寻找资源来解决我的问题。 我还是做不到。 如果有人能帮我解决这个问题,那将是真正有帮助的。 非常感谢。 我的代码是:

#include <iostream>

using namespace std;
int main()
{
    string listt[];

    string word;
    cout<< "Enter word: ";

    while (word != "Quit" ){

        cin >> word;
        listt.push_back(word);
    }
    cout << listt;

    int len ;

    len = listt.size();
    cout << len;
    for (int i=0; i < len; i++){
        cout << i;
        cout << endl;
    
    }
    return 0; 
}

共3个答案

匿名用户

您应该使用vector而不是Array:

所以不是:

string listt[]; // shouldn't compile anyway

使用:

vector<string> listt;

另外,这也是不对的:

cout << listt; // you can't print array or vector directly, so loop and print each item

另外,使用for-each而不是C样式的for

for (const auto &v : listt)
{
    cout << v << endl;
}

代码的其余部分应该没有问题。

匿名用户

在您的代码中,您将方法用于类向量。 你需要在你的程序中包含库矢量。 还需要将字符串的矢量声明为:

vector<string>listt;

如果要输出向量的每个元素,则需要使用循环。

for ( int i = 0; i < listt.size(); i++ ) cout << listt[i] << '\n';

所以不正确

cout << listt;

您的程序将看起来像:

#include <iostream>
#include <vector>

using namespace std;
int main()
{
    vector<string> listt;

    string word;
    cout << "Enter word: ";

    while (word != "Quit") {

        cin >> word;
        listt.push_back(word);
    }

    int len;
    len = listt.size();
    cout << len;

    for (int i = 0; i < len; i++) {
        cout << listt[i];
        cout << endl;

    }
    return 0;
}

匿名用户

您可能正在查找向量。 您试图创建的是一个数组,它没有任何类似push_back()的内容。

向量文档

相关问题


MySQL Query : SELECT * FROM v9_ask_question WHERE 1=1 AND question regexp '(何在|空|数组|中|添加|用户|给出|字符串|并在|c++|中找到|长度)' ORDER BY qid DESC LIMIT 20
MySQL Error : Got error 'repetition-operator operand invalid' from regexp
MySQL Errno : 1139
Message : Got error 'repetition-operator operand invalid' from regexp
Need Help?