C++;:为循环传递数组时没有打印值? 我对C++编程很陌生。每当我运行它时,它不会打印任何内容

C++;:为循环传递数组时没有打印值? 我对C++编程很陌生。每当我运行它时,它不会打印任何内容,c++,for-loop,while-loop,c++17,C++,For Loop,While Loop,C++17,我想要的是无限次地询问用户的姓名,只有在键入“退出”后才会中断。输入“quit”后,它必须打印数组中的所有项。但它没有打印任何东西。我错在哪里 这是我的密码: #include <iostream> #include <string> #include <vector> using namespace std; int count = 0; std::string arr[] = {}; void my_funct() { for (int i =

我想要的是无限次地询问用户的姓名,只有在键入“退出”后才会中断。输入“quit”后,它必须打印数组中的所有项。但它没有打印任何东西。我错在哪里

这是我的密码:

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

int count = 0;
std::string arr[] = {};

void my_funct()
{
    for (int i = 0; i < count; i++){
        std::cout << arr[i];
    }
}

int main()
{
    std::string names;
    while (true)
    {
        std::cout << "Enter your name: \n";
        getline(std::cin, names);
        if (names == "quit")
        {
            my_funct();
            break;
        }
        else
        {
            std::string arr[] = {names};
            count++;
        }
    }
}


#包括
#包括
#包括
使用名称空间std;
整数计数=0;
std::字符串arr[]={};
作废我的函数()
{
for(int i=0;istd::cout
arr
my_funct()中if-else语句中的
arr是两个不同的数组。您在if-else中声明了本地版本,在循环的每次迭代后,该版本都会被销毁。您还将其声明为长度为零的数组-这意味着它不能容纳任何元素。在您的示例中,您需要的是
std::vector
(您甚至包括了适当的头)

然后可以退出
count
变量并使用
vec.size()
(我已将
arr
重命名为
vec

#包括
#包括
#包括
使用名称空间std;
std::vec;
作废我的函数()
{
对于(int i=0;i#包括
#包括
#包括
使用名称空间std;
整数计数=0;
向量arr;
作废我的函数()
{
用于(自动ar:arr){

std::cout这是我试图更正的您的代码。如果您不理解或需要解释,请询问,我将尝试解释

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

int counet = 0;

vector<string> arr;

void my_funct()
{
    for (int i = 0; i < arr.size(); i++){
        cout << arr[i] << endl;
    }
}

int main()
{
    
    std::string names;
    while (true)
    {
        std::cout << "Enter your name: \n";
        getline(std::cin, names);
        
        if (names == "quit")
        {
            my_funct();
            break;
        }
        else
        {
            arr.push_back(names);
        }
    }
}
#包括
#包括
#包括
使用名称空间std;
int CONNET=0;
向量arr;
作废我的函数()
{
对于(int i=0;i您是否应该使用
cin.ignore()
std::string arr[]={names};
这在哪里使用?一个完全无用的语句。您想在这里使用向量吗?:
std::vector arr;arr.push_back(name);
std::string arr[]={names};
也是一个局部变量,在第一次
时超出范围
紧跟在
计数++;
仅供参考,因为您break@Roxanne,接受这个或另一个答案。两者都是正确的
#include <iostream>
#include <string>
#include <vector>
using namespace std;

int counet = 0;

vector<string> arr;

void my_funct()
{
    for (int i = 0; i < arr.size(); i++){
        cout << arr[i] << endl;
    }
}

int main()
{
    
    std::string names;
    while (true)
    {
        std::cout << "Enter your name: \n";
        getline(std::cin, names);
        
        if (names == "quit")
        {
            my_funct();
            break;
        }
        else
        {
            arr.push_back(names);
        }
    }
}