当我尝试从我的数组中打印一个字符串时,它无法正常工作(C ++)

时间:2017-10-01 02:58:31

标签: c++ arrays string io

这是我的代码:

我想要做的是让用户输入一串字符串,然后用户说出你刚才写的列表中的哪个字符串,该程序会回复给你。

#include <iostream>
#include <string>

using namespace std;

int amount = 0;
int listnum;
string inpu;


void input(string in){
cout << "Enter a word" << endl;
cin >> in;
}



int main()
{
cout << "How many strings do you want to enter." << endl;
cin >> amount;

string list1[amount];
for(int x = 0; x < amount; x++){
    input(inpu);
    list1[x] = inpu;

    if(x == amount-1){
        cout << "Which word on the list do you want to use?" << endl;
        cin >> listnum;
        cout << list1[listnum] << endl;

    }
}
}

我不确定发生了什么,所以我真的很乐意帮忙。

谢谢!

2 个答案:

答案 0 :(得分:1)

我不知道你遇到了什么问题。我看到了这个问题:

void input(string in){
    cout << "Enter a word" << endl;
    cin >> in;
}

尝试将引用传递给您的变量:

void input(string &in){
cout << "Enter a word" << endl;
cin >> in;
}

或者您可以传递指针:

void input(string *in){
cout << "Enter a word" << endl;
cin >> *in; //Now that this is a pointer, you need to add a * before the variable name when you want to access it.
}

如果传递指针,请确保使用指针调用函数:

input(&inpu);

传递指针是在C中执行它的唯一方法。除非你调用C函数,否则你可能永远不必在C ++中使用它。

答案 1 :(得分:0)

使用普通数组无法在C ++中执行您所说的操作。 C ++解决方案是使用STL库为您提供std :: vector。

#include <iostream>
#include <string>
#include <vector>

using namespace std;

    int main() {
        vector<string> list1;//This creates a vector 
        string in = "";
        int amount = 0;
        int listnum = 0;


        cout << "How many strings do you want to enter." << endl;
        cin >> amount;

        //This for loop will append the item into the vector list
        //The for loop will control how many item will be appended to the list
        for (int i = 0; i < amount; i++) {
            cout << "Enter a word" << endl;
            cin >> in;
            //The push back function will push the string into the vecot
            list1.push_back(in);
        }

        //This will ask the user for the index position of the word
        cout << "Which index on the list do you want to use?" << endl;
        cin >> listnum;

        //This line of code will output the string that the user wants
        cout << list1[listnum] << endl;


        system("pause");
        return 0;
    }