当我尝试从数组中打印一个字符串时,它不起作用(C )
When I try to print a string from my array it is not working (C++)
这是我的代码:
我要做的是让用户输入一堆字符串,然后用户说您刚刚写过的列表中的哪个字符串会向您说回来。
#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;
}
}
}
我不确定发生了什么,所以我真的会喜欢帮助。
谢谢!
我不知道您遇到了什么问题。我看到了这个问题:
void input(string in){
cout << "Enter a word" << endl;
cin >> in;
}
尝试将A 参考转到您的变量:
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 解决方案是通过使用为您提供std :: vector的STL库。
#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;
}