简体   繁体   English

我想将输入存储在数组中。 并打印数组元素,但 cout 行不工作

[英]I want to store input in array. and print the array elements but cout line isn't working

I am new in programming,我是编程新手,

basically in this program, it takes input from user and storing in array, 5 elements.基本上在这个程序中,它从用户那里获取输入并存储在数组中,5 个元素。 After loop ends it should give the elements back but it seems that the last line is not working.循环结束后它应该返回元素,但似乎最后一行不起作用。

include<iostream>
using namespace std;
int main(){
int size=5; 
string guess[size];
for (int i=0; i<size;i++){
    cin>>guess[size];
}
cout<<guess[size];
  return 0;
}

guess[size] is out of bounds. guess[size]超出范围。 The last valid index in an array with size elements is size-1 .具有size元素的数组中的最后一个有效索引是size-1 Further, string guess[size];此外, string guess[size]; is not valid C++ when size is not a constant expression.size不是常量表达式时,无效 C++。 At the very least it should be const int size = 5;至少应该是const int size = 5; . . You wrote a loop to take input and you also need a loop to print all elements.您编写了一个循环来获取输入,您还需要一个循环来打印所有元素。

This is the correct loop to read the input:这是读取输入的正确循环:

const int size=5; 
std::string guess[size];
for (int i=0; i < size; i++){
    std::cin >> guess[i];
}

You can modify it so that both input and output should use i as the loop subscript.您可以修改它,使输入和 output 都应使用 i 作为循环下标。

//cover #
#include<iostream>
using namespace std;
int main(){
    int size=5;
    string guess[size];
    for (int i=0; i<size;i++){
        cin>>guess[i];
    }
    for (int i = 0; i < size; ++i) {
        cout<<guess[i];
    }
    return 0;
}

Use Range based Loops when You want to Print whole array, so you won't get an "Out-Of-Bounds" error.当你想打印整个数组时使用基于范围的循环,这样你就不会得到“越界”错误。 Because the Index in array are Zero Based Always remember the last index is (length_of_array - 1)因为数组中的索引是从零开始永远记住最后一个索引是 (length_of_array - 1)

using namespace std;
int main()
{
    int size = 5;
    string guess[size];
    for (int i=0; i<size;i++)
    {
        cin >> guess[i];
    }
    // range based loop
    for (int i : guess)
    {
        cout << i << endl; 
    }
    return 0;
}

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

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