我得到C++语法错误

I am getting C++ syntax error

本文关键字:语法 错误 C++      更新时间:2023-10-16

这个脚本应该从键盘上读取字符,将它们存储到数组中,然后输出:

#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
void storeArraysintoStruct(char[], int);
int main()
{
    char test[] ="";
    int a = 0;
    storeArraysintoStruct(test, a);
    system("pause");
    return 0;
}
void storeArraysintoStruct(char test[], int a)
{
    int n;
    cout << "Enter number of entries: " << endl;
    cin >> n;
    int i = 0;
    for (i=0, i<n, i++)
    {
        cout << "Enter your character: " << endl;
        cin.getline(test, n);
    }
    while (i < n)
    {
        cout << test[i] << endl;
        i++;
    }
}

编辑:修复:

#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
void storeArraysintoStruct(char[], int);
int main()
{
    char test[40] = "";
    int a = 0; 
    storeArraysintoStruct(test, a);
    system("pause");
    return 0;
}
void storeArraysintoStruct(char test[], int a)
{
    int n;
    cout << "Enter number of entries: " << endl;
    cin >> n;
    int i;

    for (i=0; i < n; i++)
    {
        cout << "Enter your character: " << endl;
        cin >> test[i];
        if (test[n-1])
        {
        cout << endl;
        }
    }
     i =0;
    while (i < n)
    {
        cout << test[i] << endl;
        i++;
        if(test[n-1])
        {
            cout << endl;
        }
    }

}

但是,我得到了预期的错误:while之前的主表达式为")"answers";"。任何帮助都将不胜感激。

编辑:脚本无法按预期工作,因为它没有输出存储的字符。如有任何建议,我们将不胜感激。

注释中已经指出了语法错误。此外,正如前面提到的,在for循环之后,您永远不会重置i,这会阻止您的while循环运行。

然而,你也必须记住,这个

char test[] = "";

分配只有1个字符长的数组CCD_ 4。不能将多个字符的数据放入该数组中。换句话说,您的storeArraysintoStruct肯定会超出数组,并落入未定义的行为领域。

如果要预先分配一个更大的缓冲区以备将来在storeArraysintoStruct中使用,则必须显式指定大小。例如

char test[1000] = "";

将使CCD_ 7成为1000个字符的数组。当然,无论阵列有多大,您都有责任遵守大小限制。

附言:如果你从未在storeArraysintoStruct中使用过参数a,那么它的意义何在?